From tuvas21 at gmail.com Mon Mar 6 18:47:08 2006 From: tuvas21 at gmail.com (Tuvas) Date: 6 Mar 2006 15:47:08 -0800 Subject: Random Prime Generator/Modular Arithmetic In-Reply-To: References: <1141487100.450422.306010@v46g2000cwv.googlegroups.com> <7x1wxhlx07.fsf@ruckus.brouhaha.com> <1141512951.983754.74980@i40g2000cwc.googlegroups.com> <1141584746.985555.285570@j33g2000cwa.googlegroups.com> <6xMOf.66118$PL5.60500@newssvr11.news.prodigy.com> <1141616149.597424.13950@j52g2000cwj.googlegroups.com> <1141616798.654461.58150@j52g2000cwj.googlegroups.com> Message-ID: <1141688828.680548.179070@e56g2000cwe.googlegroups.com> Actually, there was a small bug fix that I found, and I had a teacher who told me once that there was only 5 pseudoprimes. I realized that large numbers of prime numbers were returning false, and discovered the root of the problem, which was that my M-R test ended too late... But, it works now, thankfully. I may switch soon to an upgraded version of the code, to be more efficient. But for now, I'm just glad to have it work! From alainpoint at yahoo.fr Wed Mar 8 05:34:59 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 8 Mar 2006 02:34:59 -0800 Subject: class variables for subclasses tuple In-Reply-To: <1141812400.569624.256460@i39g2000cwa.googlegroups.com> References: <1141809649.911658.90570@p10g2000cwp.googlegroups.com> <1141812400.569624.256460@i39g2000cwa.googlegroups.com> Message-ID: <1141814099.153382.209530@z34g2000cwc.googlegroups.com> As an supplement to my previous post, please find hereunder a snippet for my unsuccessful attempt (commented out snippet does not work): def superTuple(*attribute_names): nargs = len(attribute_names) class T(tuple): def __new__(cls, *args): return tuple.__new__(cls, args) class __metaclass__(type): x=property(lambda self:0) y=property(lambda self:1) z=property(lambda self:2) x=property(lambda self:self[0]) y=property(lambda self:self[1]) z=property(lambda self:self[2]) #for idx, attr_name in enumerate(attribute_names): # print 'attr name',attr_name, idx # setattr(T.__metaclass__,attr_name, property(lambda cls:idx)) #for idx, attr_name in enumerate(attribute_names): # print 'attr name',attr_name # setattr(T,attr_name, property(lambda self:self[idx])) return T if __name__ == '__main__': Point=superTuple('x','y','z') p=Point(4,7,9) assert p.x==p[0] assert p.y==p[1] assert p.z==p[2] assert Point.x==0 assert Point.y==1 assert Point.z==2 Alain From jeff at schwabcenter.com Mon Mar 27 10:33:35 2006 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Mon, 27 Mar 2006 15:33:35 GMT Subject: Python, equivalent of set command In-Reply-To: <1143465742.940093.35720@i40g2000cwc.googlegroups.com> References: <1143465742.940093.35720@i40g2000cwc.googlegroups.com> Message-ID: loial wrote: > In unix shell script I can do the following to get the status and > values returned by a unix command > > OUTPUT=`some unix command` > STATUS=$? > if [ $STATUS -ne 0 ] > then > exit 1 > else > set $OUTPUT > VAL1=$1 > VAL2=$2 > VAL3=$3 > fi > > How can I achieve the same in python? > > I know how to run it via the os.system command and return the status, > but how do I return the values too? http://docs.python.org/lib/node241.html 6.8.3.1 Replacing /bin/sh shell backquote output=`mycmd myarg` ==> output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] The popen object also has a 'returncode' attribute. From finite.automaton at gmail.com Mon Mar 6 12:05:19 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 6 Mar 2006 09:05:19 -0800 Subject: Simulation Programming Skills and Python References: Message-ID: <1141664719.527273.190710@u72g2000cwu.googlegroups.com> Object oriented languages lend themselves fairly well to this sort of modeling, and a strong programmer in any language should be able to take a good description of a well thought-out model and write some code for it. However, by far the harder part is designing a good model. Asking whether all programmers are capable of that is sort of like asking whether all carpenters are architects. As for Python, it's a good language for prototyping. The development cycle moves very fast, so one can experiment with many different ideas more quickly than in Java or C++. The price, however, is execution speed. There are extension modules like the scipy suite which can reclaim some lost speed, but Python will generally be slower than compiled languages. From robert.kern at gmail.com Fri Mar 31 02:31:35 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 31 Mar 2006 01:31:35 -0600 Subject: Low Pass Hamming filter design In-Reply-To: <1143789120.077514.241770@j33g2000cwa.googlegroups.com> References: <1143724433.200046.17700@u72g2000cwu.googlegroups.com> <1143789120.077514.241770@j33g2000cwa.googlegroups.com> Message-ID: LabWINC wrote: > Is there someone that can help me? On this list, maybe not. But the scipy list is scipy-users at scipy.net . http://www.scipy.net/mailman/listinfo/scipy-user -- Robert Kern robert.kern at gmail.com "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 root at randpoly.com Tue Mar 21 03:13:32 2006 From: root at randpoly.com (randpoly.com PostMaster) Date: Tue, 21 Mar 2006 13:43:32 +0530 Subject: Error sending message [1142852913051.1792.rpppl] from [randpoly.com] Message-ID: <20060321082429.E9BDD2E1F32@smtp41.smtp4u.com> [<00>] V-POP3bounce: Rcpt=[jeremy at nirvani.net];Error=[550 Error: Invalid Attachment] [<01>] Error sending message [1142852913051.1792.rpppl] from [randpoly.com]. ID: Mail From: Rcpt To: Server: [209.120.245.170] [<02>] The reason of the delivery failure was: 550 Error: Invalid Attachment [<05>] Here is listed the initial part of the message: Received: from python.org (192.168.0.24:4203) by smtp.randpoly.com with [V-POP3Mail (Win32/Ix86) ESMTP Server] id for from ; Mon, 20 Mar 2006 16:38:28 +0530 From: python-list at python.org To: jeremy at nirvani.net Subject: Good day Date: Mon, 20 Mar 2006 16:50:20 +0530 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_0012_F35E4AFF.7BDAC5B9" X-Priority: 3 X-MSMail-Priority: Normal From roy at panix.com Fri Mar 10 09:19:40 2006 From: roy at panix.com (Roy Smith) Date: Fri, 10 Mar 2006 09:19:40 -0500 Subject: Why python doesn't use syntax like function(, , x) for default parameters? References: <44115054$0$14937$834e42db@reader.greatnowhere.com> Message-ID: In article , Antoon Pardon wrote: > Op 2006-03-10, Roy Smith schreef : > > "Dmitry Anikin" wrote: > >> There are often situations when a function has independent > >> parameters, all having reasonable defaults, and I want to > >> provide just several of them. In fact, I can do it using > >> keyword parameters, but it's rather long and you have to > >> remember/lookup names of parameters. > > > > Specifying the names of the keyword parameters costs you a little typing > > once, but saves everybody (including yourself) a lot of grief later when > > you're trying to figure out what the heck your code does 6 months later. > > Could you explain what is so hard in figuring out: > > func(,,4) Because while I probably remember what func does (especially if it's well named), it's less likely that I remember all the arguments it takes, and even less that I remember what order they come in. Let's say I've got a function which makes a network connection. It takes optional arguments for a port number to connect to, a timeout (in seconds) and a buffer size (in kbytes) to use. If we used your syntax, what does "connect (,,20)" mean? You have to go look up the definition of the function to find out, don't you? But, if I wrote "connect (port=20)", it's obvious to anybody reading the code what the 20 is. From robert.kern at gmail.com Wed Mar 8 14:15:49 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 08 Mar 2006 13:15:49 -0600 Subject: reshape an array? In-Reply-To: <1141844720.242225.322220@p10g2000cwp.googlegroups.com> References: <1141844720.242225.322220@p10g2000cwp.googlegroups.com> Message-ID: KraftDiner wrote: > I have a 2D array. Say it is 10x10 and I want a 1D Array of 100 > elements... > What is the syntax? > > oneD = reshape(twoD, (100,1)) > or > oneD = reshape(twoD, (1,100)) > > One I guess is the transpose of the other but both seem to be > arrays of arrays... The mailing list for numpy is numeric-discussion at lists.sourceforge.net, and you may get faster/better help there. But: oneD = reshape(twoD, (100,)) -- Robert Kern robert.kern at gmail.com "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 challman at gmail.com Thu Mar 9 14:47:11 2006 From: challman at gmail.com (challman at gmail.com) Date: 9 Mar 2006 11:47:11 -0800 Subject: convert hex to decimal Message-ID: <1141933631.455001.263320@z34g2000cwc.googlegroups.com> I'm executing the following: def run(self): # get ntp_column pop = os.popen("snmpget -v 1 -c SLI398uwiE " + self.host + " 1.3.6.1.4.1.9.9.168.1.1.9.0\n") popS = string.join(pop.readlines()) if "Unknown host" in popS: output.write(self.host + " - unknow host.\n") return elif "Error in packet" in popS: output.write(self.host + " - error in SNMP query.\n") return popS = popS.split('INTEGER: ') clmn = str(popS[1].replace('\n', '')) time.sleep(1) # get ntpRootDelay pop = os.popen("snmpget -v 1 -c readonly " + self.host + " 1.3.6.1.4.1.9.9.168.1.2.1.1.13." + clmn + "\n") popS = string.join(pop.readlines()) if "Unknown host" in popS: output.write(self.host + " - unknow host.\n") return elif "Error in packet" in popS: output.write(self.host + " - error in SNMP query.\n") return popS = popS.split('Hex-STRING: ') delay = popS[1].replace('\n', '') delay = delay.replace(' ', '') The output from the second popen is: SNMPv2-SMI::enterprises.9.9.168.1.2.1.1.13.51858 = Hex-STRING: 00 00 00 26 I need to get the Hex-STRING into the following format: 0.0038.. I know how to covert 26 to 38 but I haven't figured out how to pad it or place the decimal point between the while number and the decimal. From tgrav at mac.com Wed Mar 22 14:35:29 2006 From: tgrav at mac.com (Tommy Grav) Date: Wed, 22 Mar 2006 14:35:29 -0500 Subject: Newbie: Print question In-Reply-To: References: Message-ID: Thanks. That works. Like I said I am a newbie :) Cheers Tommy On Mar 22, 2006, at 1:17 PM, Fredrik Lundh wrote: > Tommy Grav wrote: > >> for testobs in obslist: >> print testobs.printmpc() > > print. > >> def printmpc(self): >> if self.mag!="": >> print "%14s %12.5f %5.2f %6.2f %8.3f %3i" > > and print. > >> I don't understand where these None's are coming from. > > for each testobs, you're printing stuff inside the printmpc method, > and you're > then printing the return value from the method. removing the extra > print > > for testobs in obslist: > testobs.printmpc() > > should fix this. > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list 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: From paddy3118 at netscape.net Sat Mar 4 14:39:11 2006 From: paddy3118 at netscape.net (Paddy) Date: 4 Mar 2006 11:39:11 -0800 Subject: XP rich text cut-n-paste Message-ID: <1141501151.073307.281850@u72g2000cwu.googlegroups.com> Hi, Is their a colourized editor/shell that allows you to cut and paste the colourized text? Idle, SPE, Eclipse, and pythonwin all seem to nicely colourize both command line input as well as editor windows but when I cut and paste (in this case, into OpenOffice Writer), even the paste-special menu just allows the pasting of un-adorned text. i have a work-around: gvim coourizes and allows export as html, but it is long-winded. Thanks in advance, Paddy. From vinay_sajip at yahoo.co.uk Wed Mar 29 12:44:55 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 29 Mar 2006 09:44:55 -0800 Subject: logging module, multiple handlers References: <1143645929.412098.282060@v46g2000cwv.googlegroups.com> Message-ID: <1143654295.284589.231930@i40g2000cwc.googlegroups.com> bneron at gmail.com wrote: > I use the logging module include in Python 2.4 distribution, and I 'd > like to have a logger witth several Handlers . > I know how to do this by coding in python, but could I specify this > directly in the logger configuration file? See in http://docs.python.org/lib/logging-config-fileformat.html the text which says, "The handlers entry is a comma-separated list of handler names, which must appear in the [handlers] section. These names must appear in the [handlers] section and have corresponding sections in the configuration file." So...add multiple handler names in the "handlers" entry for a logger to get those handlers added to the logger. From paddy3118 at netscape.net Thu Mar 23 14:59:14 2006 From: paddy3118 at netscape.net (Paddy) Date: 23 Mar 2006 11:59:14 -0800 Subject: RELEASED Python 2.4.3, release candidate 1 References: Message-ID: <1143143954.598849.157470@v46g2000cwv.googlegroups.com> I followed the links to the coverity page that shows their table of errors found, and subsequently fixed in tools used for the LAMP stack. They say that they informed the maintainers of the software about the precise errors found and the number of errors has been tracked since then. It seems there page has been updated with the results of the latest Python release o i thought I'd put a marketing spin on the data to show which projects have been fixing their bugs. I added the column showing % bugs fixed and sorted on that column to highlight just what you Python maintainers have achieved: Project Current Original Percent Lines of Defects / defects defects fixed code KLOC AMANDA 0 108 100.00% 88879 0 Python 0 96 100.00% 269609 0 Samba 0 216 100.00% 313893 0 XMMS 0 6 100.00% 117099 0 ethereal 11 143 92.31% 1131213 0.01 icecast 2 12 83.33% 37251 0.05 SQLite 6 31 80.65% 54257 0.11 PHP 47 204 76.96% 426559 0.11 wxWidgets 30 73 58.90% 310917 0.1 Net-SNMP 61 148 58.78% 173203 0.35 Gaim 51 113 54.87% 325646 0.16 Firefox 50 108 53.70% 305453 0.16 OpenSSL 35 66 46.97% 200813 0.17 xine 196 347 43.52% 578738 0.34 MPlayer 192 284 32.39% 489636 0.39 gcc 103 140 26.43% 696310 0.15 NetBSD 2529 3230 21.70% 5078094 0.5 Perl 70 89 21.35% 483331 0.15 Linux-2.6 847 1062 20.24% 3171895 0.27 apache-http 26 32 18.75% 127974 0.2 X.org 1448 1681 13.86% 2353980 0.62 Squid 48 53 9.43% 175345 0.27 Gnome 849 896 5.25% 1311031 0.65 tcl 67 69 2.90% 120865 0.55 OpenLDAP 154 158 2.53% 258144 0.6 snort 47 48 2.08% 94111 0.5 FreeBSD 632 635 0.47% 1582166 0.4 PostgreSQL 294 295 0.34% 816869 0.36 Inetutils 29 29 0.00% 72681 0.4 OpenVPN 7 7 0.00% 69905 0.1 ProFTPD 26 26 0.00% 90027 0.29 Firebird 194 163 -19.02% 271192 0.72 The original data is from http://scan.coverity.com/ on the day of this posting. - Paddy -- http://paddy3118.blogspot.com/ From bencvt at gmail.com Tue Mar 21 18:51:43 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 21 Mar 2006 15:51:43 -0800 Subject: Simple py script to calc folder sizes In-Reply-To: <1142983179.378155.92340@v46g2000cwv.googlegroups.com> References: <1142983179.378155.92340@v46g2000cwv.googlegroups.com> Message-ID: <1142985103.636314.268890@z34g2000cwc.googlegroups.com> Caleb Hattingh wrote: > Unless you have a nice tool handy, calculating many folder sizes for > clearing disk space can be a click-fest nightmare. Looking around, I > found Baobab (gui tool); the "du" linux/unix command-line tool; the > extremely impressive tkdu: http://unpythonic.net/jeff/tkdu/ ; a python > script I didn't really understand at > http://vsbabu.org/webdev/zopedev/foldersize.html (are these "folder > objects" zope thingies?); there are also tools that can add a > "foldersize" column into Explorer on Windows > (foldersize.sourceforge.net, for example); the superb freeCommander > file-manager (win32) has the functionality built in, and so on. You also might want to take a look at KDirStat (http://kdirstat.sourceforge.net/) and its win32 counterpart, WinDirStat (http://windirstat.sourceforge.net/). > "du" is closest to what I was looking for, but is not immediately > cross-platform: I know I can probably get it through Cygwin, and there > is probably a win32 binary or clone around somewhere Try http://unxutils.sourceforge.net/ ... much quicker to set up than Cygwin. A pure Python port of du (and other unix utilities) would be cool, though. --Ben From reply.in.the.newsgroup at my.address.is.invalid Sat Mar 4 08:00:04 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 04 Mar 2006 14:00:04 +0100 Subject: How to except the unexpected? References: Message-ID: <8n3j02ld5rohugr381n2k2pjec4em24f2g@4ax.com> Roy Smith: >In theory, all exceptions which represent problems with the external >environment (rather than programming mistakes) should derive from >Exception, but not from StandardError. Are you sure? """ The class hierarchy for built-in exceptions is: Exception +-- StandardError | +-- KeyboardInterrupt | +-- ImportError | +-- EnvironmentError | | +-- IOError """ http://www.python.org/doc/current/lib/module-exceptions.html -- Ren? Pijlman From grante at visi.com Sun Mar 12 23:58:36 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 13 Mar 2006 04:58:36 -0000 Subject: how exactly do binary files work in python? References: <3aGdnZUhQZn-I4nZRVn-jw@speakeasy.net> <1219p653bvv2vd8@corp.supernews.com> <1hc3qn2.1sum5na1x7bz08N%aleaxit@yahoo.com> Message-ID: <1219uvs7jebqu21@corp.supernews.com> On 2006-03-13, Alex Martelli wrote: > Grant Edwards wrote: > ... >> > What does a binary file do that a text file doesn't, aside >> > from not converting the end of line characters? >> >> Nothing. It's the end-of-line conversion that can break binary >> data. > > I believe that a "control-Z" (ord(26)) in a file that's being read as > text, on Windows, is also taken as an end-of-file indication. Ah yes. IIRC, that's left over from CP/M, where the filesystem didn't keep a file length for files other than a block count. It was up to the application(s) to keep track of where in that last block the "real" data ended. -- Grant Edwards grante Yow! I wonder if I ought at to tell them about my visi.com PREVIOUS LIFE as a COMPLETE STRANGER? From richard at nospam.com Wed Mar 22 15:39:51 2006 From: richard at nospam.com (Richard Townsend) Date: Wed, 22 Mar 2006 20:39:51 +0000 Subject: Louie + Twisted Message-ID: <5jeawpocz0zy$.1ertemu07opya.dlg@40tude.net> I recently came across the Louie package (http://louie.berlios.de/) I am particularly interested in the TwistedDispatchPlugin, however the documentation is very sparse. Does anyone have some example code showing how to use it, please? -- Richard From paraic.gallagher at gmail.com Wed Mar 22 09:16:17 2006 From: paraic.gallagher at gmail.com (Paraic Gallagher) Date: Wed, 22 Mar 2006 14:16:17 +0000 Subject: Default/editable string to raw_input In-Reply-To: References: Message-ID: <44215C31.30300@gmail.com> Sybren Stuvel wrote: >My opinion: let the user edit the configuration file using his/her >favourite text editor. Someone configuring a test suite should >certainly be able to edit a text file. > >Sybren > > While I agree in principal to your opinion, the idea is that an absolute moron would be able to configure a testcell with smallest amount of effort possible. Moreover, I am curious as to whether somebody else out there knows if there is a solution to the problem. Paraic. From Serge.Orlov at gmail.com Fri Mar 24 23:24:20 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 24 Mar 2006 20:24:20 -0800 Subject: =?utf-8?B?UmU6IGVuY29kaW5nIHByb2JsZW1zICjDqSBhbmQgw6gp?= References: <442378fa$1@news.eftel.com> <44247837.10305@v.loewis.de> Message-ID: <1143260660.598726.269990@i39g2000cwa.googlegroups.com> Martin v. L?wis wrote: > John Machin wrote: > >> and, for things like u'\u0565\u0582' (ARMENIAN SMALL LIGATURE ECH > >> YIWN), it does not even work. > > > > Sorry, I don't understand. > > 0565 is stand-alone ECH > > 0582 is stand-alone YIWN > > 0587 is the ligature. > > What doesn't work? At first guess, in the absence of an Armenian > > informant, for pre-matching normalisation, I'd replace 0587 by the two > > constituents -- just like 00DF would be expanded to "ss" (before > > upshifting and before not caring too much about differences caused by > > doubled letters). > > Looking at the UnicodeData helps here: > > 00DF;LATIN SMALL LETTER SHARP S;Ll;0;L;;;;;N;;German;;; > 0587;ARMENIAN SMALL LIGATURE ECH YIWN;Ll;0;L; 0565 0582;;;;N;;;;; > > So U+0587 is a compatibility character for U+0565,U+0582. Not sure > what the rationale for *this* compatibility character is, but in many > cases, they are in Unicode only for compatibility with some existing > encoding - if they had gone through the proper Unification, they should > not have been introduced as separate characters. The problem is that U+0587 is a ligature in Western Armenian dialect (hy locale) and a character in Eastern Armenian dialect (hy_AM locale). It is strange the code point is marked as compatibility char. It either mistake or political decision. It used to be a ligature before orthographic reform in 1930s by communist government in Armenia, then it became a character, but after end of Soviet Union (1991) they started to think about going back to old orthography. Though it hasn't happened and it's not clear if it will ever happen. So U+0587 is a character. By the way, this char/ligature is present on both Western and Eastern Armenian keyboard layouts: http://www.datacal.com/products/armenian-western-layout.htm It is between 9 and (. In Eastern Armenian this character is used in words ? ( the word "and" in English) , ??? ( "sun" in English) and hundreds others. Needless to say how many documents exist with this character. > > In many cases, ligature characters exist for typographical reasons; > other examples are > > FB00;LATIN SMALL LIGATURE FF;Ll;0;L; 0066 0066;;;;N;;;;; > FB01;LATIN SMALL LIGATURE FI;Ll;0;L; 0066 0069;;;;N;;;;; > FB02;LATIN SMALL LIGATURE FL;Ll;0;L; 0066 006C;;;;N;;;;; > FB03;LATIN SMALL LIGATURE FFI;Ll;0;L; 0066 0066 0069;;;;N;;;;; > FB04;LATIN SMALL LIGATURE FFL;Ll;0;L; 0066 0066 006C;;;;N;;;;; > > In these cases, it is the font designers which want to have code points > for these characters: the glyphs of the ligature cannot be automatically > derived from the glyphs of the individual characters. I can only guess > that the issue with that Armenian ligature is similar. > > Notice that the issue of U+00DF is entirely different: it is a character > on its own, not a ligature. That a common transliteration for this > character exists is again a different story. > > Now, as to what might not work: While compatibility decomposition > (NFKD) converts \u0587 to \u0565\u0582, the reverse process is not > supported. This is intentional, of course: there is no "canonical" > compatibility character for every decomposed code point. Seems like NFKD will damage Eastern Armenian text (there are millions of such documents). The result will be readable but the text will look strange to the person who wrote the text. Serge. From fake at nospam.no Fri Mar 3 04:26:04 2006 From: fake at nospam.no (Blackbird) Date: Fri, 3 Mar 2006 10:26:04 +0100 Subject: How much does Python optimize? Message-ID: Hello! I think for i in range(10): is more readable than a while loop with explicit incrementation of i. However, range(10) in the command interpreter obviously returns a list. Is this list optimized away in the code above, or is it actually constructed internally? (With, say, CPython in one of the recent versions.) From eugene at boardkulture.com Tue Mar 21 05:52:30 2006 From: eugene at boardkulture.com (3KWA) Date: 21 Mar 2006 02:52:30 -0800 Subject: New-style Python icons In-Reply-To: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> Message-ID: <1142938350.321554.69260@t31g2000cwb.googlegroups.com> Superb! How about getting them in the 2.5 release? Part of the reason why I am asking is that I am not sure what I have to do to get Win XP to use these instead of the one coming with 2.4.2. Cheers, EuGeNe From johnjsal at NOSPAMgmail.com Wed Mar 8 19:09:08 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Mar 2006 19:09:08 -0500 Subject: question about slicing with a step length Message-ID: Given: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] can someone explain to me why numbers[10:0:-2] results in [10, 8, 6, 4, 2]? I thought the first index, whether going forward or backward, was inclusive. And there is no index of 10 in this list, so what is it referring to? Thanks. From cito at online.de Wed Mar 15 05:00:33 2006 From: cito at online.de (Christoph Zwerschke) Date: Wed, 15 Mar 2006 11:00:33 +0100 Subject: Python Debugger / IDE ?? In-Reply-To: <1142357338.313046.139060@i39g2000cwa.googlegroups.com> References: <1142357338.313046.139060@i39g2000cwa.googlegroups.com> Message-ID: krypto.wizard at gmail.com schrieb: > Is there any editor or IDE in Python (either Windows or Linux) which > has very good debugging facilites like MS VisualStudio has or something > like that. > > I like SPE but couldn't easily use winPDP. I need tips to debug my code > easily. You can try out PyScripter, a relatively new Python IDE that is completely free and has nice debugging and unit testing facilities. The latest version is available here: http://mmm-experts.com/Downloads.aspx?ProductID=4&ShowVersionInfo=yes -- Christoph From rune.strand at gmail.com Fri Mar 31 19:06:45 2006 From: rune.strand at gmail.com (Rune Strand) Date: 31 Mar 2006 16:06:45 -0800 Subject: Exception handling....dumb question? In-Reply-To: <1143849093.457940.294150@g10g2000cwb.googlegroups.com> References: <1143849093.457940.294150@g10g2000cwb.googlegroups.com> Message-ID: <1143850005.220496.15890@e56g2000cwe.googlegroups.com> kbperry wrote: > In Python, > When using the default except (like following) > > try: > some code that might blow up > > except: > print "some error message" > > > Is there a way to show what error it is throwing? > > Like in Java, you can do > catch (Exception e){ > System.out.println(e); > } > > Or something like that. > > Is there an equivalent way to do this in Python? see sys.exc_info( ) From johnjsal at NOSPAMgmail.com Wed Mar 1 14:55:12 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 01 Mar 2006 19:55:12 GMT Subject: calling a class method Message-ID: I'm reading about class methods now and I have a question about calling them. I know it is wrong of me to assume it needs to work in a parallel manner to an instance method, but I'm curious why it doesn't. Here's the book's example: class Multi: def imeth(self, x): print self, x def cmeth(cls, x): print cls, x cmeth = classmethod(cmeth) Now, when you call the instance method through the class, you say: obj = Multi() Multi.imeth(obj, 3) But when you call the class method through an instance, you say: obj.cmeth(3) Why don't you have to explicitly pass the class name as the first argument when you don't qualify the call with the class name? the cmeth function has two arguments, so I would think you'd get an exception (as you would with Multi.imeth(3)). But do class methods automatically extract the class name from the qualifying instance and implicitly send it to the method? Thanks. From maxm at mxm.dk Wed Mar 8 07:08:45 2006 From: maxm at mxm.dk (Max M) Date: Wed, 08 Mar 2006 13:08:45 +0100 Subject: Simple questions on use of objects (probably faq) In-Reply-To: References: Message-ID: <440EC94D.5010309@mxm.dk> Brian Elmegaard wrote: > Hi, > > I am struggling to understand how to really appreciate object > orientation. I guess these are FAQ's but I have not been able to find > the answers. Maybe my problem is that my style and understanding are > influenced by matlab and fortran. > What I hoped I could do: > class Foo: > def __init__(self,self.x): > continue > y=[] > y.append(Foo(10.0)) > y.append(Foo(110.0)) > y.append(Foo(60.0)) > > ys=([y[].x]) > y_max=max(y[].x) > y_min=min(y[].x) > > yz=[y[:-1].x-y[1:].x] It is hard to tell what you are trying to do here. But here is a shot at parts of the code. class Foo: def __init__(self, x): self.x = x y = [Foo(10.0), Foo(110.0), Foo(60.0)] x_values = [o.x for o in y] y_max = max(x_values) y_min = min(x_values) Otherwise you could try and describe with words what you are getting at. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From aahz at pythoncraft.com Mon Mar 20 18:45:36 2006 From: aahz at pythoncraft.com (Aahz) Date: 20 Mar 2006 15:45:36 -0800 Subject: Function params with **? what do these mean? References: <1142887602.977736.300990@u72g2000cwu.googlegroups.com> Message-ID: In article , Dave Hansen wrote: >On 20 Mar 2006 12:46:43 -0800 in comp.lang.python, "J Rice" > wrote: >> >>I'm sorry for such a basic question, but I haven't been able to phrase >>a search that gets me an answer and my books are totally silent on >>this. I have seen a number of python function defs that take >>parameters of the form (**param1). Looks like a pointer... but my >>books on python (basic as they are) don't make a mention. What is >>this? > >It's a way of accepting a varying number of named arguments. In the >function, the parameter becomes a dictionary with parameter names as >the keys corresponding to the passed parameter values. > >It's harder to explain than understand. Try playing with the >following function in the python interpreter: > > def test(a,b='b', *c, **d): > print a,b,c,d Personally, I think it's a Good Idea to stick with the semi-standard names of *args and **kwargs to make searching easier... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From sybrenUSE at YOUR.thirdtower.com.IMAGINATION Sun Mar 5 11:09:20 2006 From: sybrenUSE at YOUR.thirdtower.com.IMAGINATION (Sybren =?UTF-8?B?U3TDvHZlbA==?=) Date: Sun, 05 Mar 2006 17:09:20 +0100 Subject: Why I chose Python over Ruby References: <1141573450.667103.8930@z34g2000cwc.googlegroups.com> Message-ID: Francois wrote: > I discovered Python a few months ago and soon decided to invest time > in learning it well. While surfing the net for Python, I also saw > the hype over Ruby and tried to find out more about it, before I > definitely embarked on studying and practicing Python. I recently > found two sufficient answers for choosing Python - which is a > personal choice and others may differ, but I'd like to share it > anyway Thanks for sharing that. I had a gut feeling Python would be better than Ruby, but I never took the time to study Ruby. Now I do have some nice stones to throw at Ruby-fanatics ;-) Sybren From fredrik at pythonware.com Mon Mar 13 16:32:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Mar 2006 22:32:58 +0100 Subject: Is this possible in Python? References: <1142238871.199749.243470@p10g2000cwp.googlegroups.com><1142282467.270698.142780@p10g2000cwp.googlegroups.com><4415daf9$1_3@newspeer2.tds.net> <1142284706.609161.128540@e56g2000cwe.googlegroups.com> Message-ID: alainpoint at yahoo.fr wrote: > I don't want a better way, i just want a solution to the problem as > described! any special reason you cannot use Python to write Python programs, instead of demanding that someone else wastes time inventing a non- portable solution to a braindead problem? what's wrong with you? From jeffrey at fro.man Wed Mar 22 12:15:16 2006 From: jeffrey at fro.man (Jeffrey Froman) Date: Wed, 22 Mar 2006 09:15:16 -0800 Subject: Server.sendmail with no "to_addrs" parameter. References: <1143026321.129185.109310@j33g2000cwa.googlegroups.com> Message-ID: <12231h0q5531se8@corp.supernews.com> EdWhyatt wrote: > I would like to have the ability to send a mail > message with no-one email address in the To field. The to_addrs parameter is for the SMTP "RCPT TO", which must contain at least one address. It has nothing to do with the To: header of the email. You can *also* add the recipient addresses to either of the Cc: or To: header fields as necessary, or leave them out of any header (the equivalent of adding the addresses to the Bcc: field.) As Arne Ludwig pointed it, it may not be RFC compliant to leave an entirely blank To: header, but in either case, the To: header need not contain any of the addresses specified in the to_addrs list. Jeffrey From peter at engcorp.com Thu Mar 30 11:30:37 2006 From: peter at engcorp.com (Peter Hansen) Date: Thu, 30 Mar 2006 11:30:37 -0500 Subject: How to determine an object is "scriptable" In-Reply-To: <1143728926.215531.276550@e56g2000cwe.googlegroups.com> References: <1143726903.153135.317880@j33g2000cwa.googlegroups.com> <4927udFmla3dU1@news.dfncis.de> <1143728926.215531.276550@e56g2000cwe.googlegroups.com> Message-ID: abcd wrote: > Daniel Evers wrote: > >>Right. You can check this e.g. with >> >> hasattr(x, "__getitem__") >> >>because the __getitem__ method is used for indexing. > > Thanks...that is what I was looking for! Maybe, but it's not a particularly Pythonic way of doing it. Better is probably something like this: try: x[0] x_is_subscriptable = True except TypeError: x_is_subscriptable = False -Peter From rurpy at yahoo.com Mon Mar 20 13:11:55 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 20 Mar 2006 10:11:55 -0800 Subject: Python equivalent of Perl-ISAPI? In-Reply-To: References: <1142657781.197131.222440@g10g2000cwb.googlegroups.com> <1142790625.227356.48830@i40g2000cwc.googlegroups.com> <1142865756.452672.57930@v46g2000cwv.googlegroups.com> <1142877087.441903.240840@v46g2000cwv.googlegroups.com> Message-ID: <1142878315.504465.191490@z34g2000cwc.googlegroups.com> Steve Holden wrote: > rurpy at yahoo.com wrote: > > Pure cgi is too slow. "Active Scripting" means ASP, yes? > > I need something that will do cgi scripts (a lot of which I already > > have > > and can modify but don't want to rewrite extensively, partly because > > of time issues, partly because I want to preserve some degree of > > portability back to a unix environment.). I want something that does > > for IIS what mod_python does for apache. Fastcgi looked scary even > > on unix plaforms, seems like an act of desperation on Windows, > > > Yes, ASP is Active Scripting. > > Remember to use <@ LANGUAGE="PYTHON" @> Except I need cgi, not asp, for the reasons i gave. From me at privacy.net Mon Mar 27 08:23:40 2006 From: me at privacy.net (Dan Sommers) Date: Mon, 27 Mar 2006 08:23:40 -0500 Subject: Difference between 'is' and '==' References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <4427d287$0$38669$edfadb0f@dread12.news.tele.dk> Message-ID: On Mon, 27 Mar 2006 14:52:46 +0200, Joel Hedlund wrote: > ... According to PEP8 (python programming style guidelines) you should > use 'is' when comparing to singletons like None. I take this to also > include constants and such ... This does *not* also mean constants and such: Python 2.4.2 (#1, Feb 22 2006, 08:02:53) [GCC 4.0.1 (Apple Computer, Inc. build 5247)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> a = 123456789 >>> a == 123456789 True >>> a is 123456789 False >>> Regards, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From jjl at pobox.com Wed Mar 22 20:00:52 2006 From: jjl at pobox.com (John J. Lee) Date: 23 Mar 2006 01:00:52 +0000 Subject: COM Client / Server creation? References: <1143060785.381056.208660@g10g2000cwb.googlegroups.com> <1143061924.070461.72060@t31g2000cwb.googlegroups.com> Message-ID: <87ek0urn3v.fsf@pobox.com> "Dan" writes: > Ive got the chapter from the net on COM. It looks pretty old, 2000. > Also the very first example in the chapter on COM doesn't seem to work. > Is what I am wanting to do possible with Python? As long as you're doing IDispatch, essentially anything is possible with pywin32's COM support. What went wrong with the first example in the book? Not covered in the book, and particularly useful for implementing native clients and servers is ctypes / comtypes (but still not stable; also, I've only personally used it for writing a client, and a very simple one at that): http://starship.python.net/crew/theller/ctypes/com.html John From jcoleman at franciscan.edu Fri Mar 3 12:05:02 2006 From: jcoleman at franciscan.edu (John Coleman) Date: 3 Mar 2006 09:05:02 -0800 Subject: Does '#hash' mean anything in IDLE? In-Reply-To: References: <1141331534.634181.275880@p10g2000cwp.googlegroups.com> <1141332159.625375.40540@e56g2000cwe.googlegroups.com> <3TINf.1719$No6.40137@news.tufts.edu> <1141394786.531934.134920@t39g2000cwt.googlegroups.com> Message-ID: <1141405501.950172.54370@i39g2000cwa.googlegroups.com> Blackbird wrote: > John Coleman skrev: > > > John Salerno wrote: > >> John Coleman wrote: > >>> John Coleman wrote: > >>>> Greetings, > >>>> I am currently trying to learn Python through the excellent > >>>> "Learning Python" book. > >> > >> me too! > >> > >>> It isn't just #hash, but also things like #dict, #int, #len at the > >>> start of a comment line which defeats IDLE's colorization algorithm. > >>> Interestingly, things like #while or #for behave as expected so it > >>> seems to be built-ins rather than keywords which are the problem. To > >>> answer my own question - this is pretty clearly a (harmless) bug. > >> > >> also notice that putting a space after # stops the problem > > > > How do you like Python so far? I like dictionary objects the best so > > far. I'm coming to Python from VBScript, so I already knew the value > > of such things, but in Python they are better supported. > > > > Here is the program I was talking about, which *really* shows the > > power of dictionaries: > > > > > **************************************************************************** > ************* > > > > #Python program to discover word with most 1-word anagrams > >[...] > > Nice! > > I think this simpler version of letter_hash should work too: > > def letter_hash(word): > w = [c for c in word] > w.sort() > return "".join(w) Nice suggestion. No need to actually count the multiplicity as long as you don't lose the information. Your function is much more readable than mine. -John Coleman From aleaxit at yahoo.com Mon Mar 20 21:51:56 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Mar 2006 18:51:56 -0800 Subject: Remote teamwork anecdotes References: <1hceomq.1whcmq2114jly6N%aleaxit@yahoo.com> <2op3f3-uf6.ln1@lairds.us> Message-ID: <1hcigpy.13ky51j19u3eevN%aleaxit@yahoo.com> Dan Sommers wrote: ... > Design meetings and similar almost have to be face to face. Agreed. > OTOH, once the design is set, leave me alone and let me > simulate it or code it, and maybe even get it past the first > round of testing and tweaking/fixing. The last thing I want > now is someone micro-managing and/or interrupting my every > rinse, lather, repeat cycle. While what *I* want, ideally, is pair programming -- somebody sitting right at my side, alternating with me in controlling keyboard and mouse, and in verbalizing what he or she is coding -- that's part of the huge productivity boost I observe in a co-located team... that pair programming works SO much better that way, that even with the best remote cooperation tools (subethaedit onwards). If I can't have pair programming, second-best is extremely frequent code reviews and submits into the working branch, again facilitated by proximity -- any question is best asked and answered f2f, often with whiteboard &c. Phone (VOIP or not), teleconferencing, IRC or other chats, &c, are pale substitutes, just as you find they are at design meeting. Maybe another way to put it is: in test-driven development (or its close equivalent, behavior-driven development, which I haven't tried IRL yet but sounds interesting) a LOT of design is happening in ways that intermix at EXTREMELY fine grain with coding and testing. No "big design up front", no trace of "waterfall", but rather, very iterative and dynamic processes (including planning and estimating -- they don't happen quite as continuously, but can't wait for "occasional" meetings either). Wanna talk debugging? I think solo debugging is even worse than solo programming -- when I just CAN'T have a debugging partner for a sufficiently nasty bug (race conditions are the worst, but there are many other categories vying for that title;-), I'll turn to one of my beloved plushies (I'm firmly convinced the baby tiger is by far the most effective debugging partner for most bugs, though Tux the Penguin has a knack for helping spot bugs that aren't MY fault but rather the compiler's &c -- since I've been using Python for most of my coding for years, poor Tux hasn't seen much action recently) -- I talk out loud to the plushy-partner to make narratives out of expected and observed occurrences. But a *LIVE* partner, actively checking out the coherence of my narratives and challenging them and proposing alternatives, is 10 times more effective... the plushies don't even talk back (except in debugging sessions that have gone on for *FAR* too long;-). Yes, there IS a place for long solo rides -- but in my experience that's normally one, maybe two days a week; that may vary by team, by project, and by person (I deal with interrupts better than most people, and I'm keener on all sorts of social interaction, bonding and networking, _including_ small chat, than 99% of the top techies I've met and worked with), but I doubt the effective range is any wider than 0 to 2.5 days/week. And even if I'm wrong, and a Joe Supercoder I've never met works best with 3 days a week of solo effort, 3 days of solo coding plus 2 of strong in-person interaction is NOT the same thing as, say, 3 _weeks_ of solo coding plus 2 of close in-person presence. Essentially, to support "non colocated" team, you can't really have the team meet in-person for more than about one week every month -- in my experience, that just isn't anywhere like enough to get top productivity (in projects conducted by agile methods -- if you're NOT using agile methods, but either "seat of the pants" or "waterfall", you have far worse problems to deal with than where people are located;-). Alex From scott.daniels at acm.org Fri Mar 10 00:52:20 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 09 Mar 2006 21:52:20 -0800 Subject: Help with a reverse dictionary lookup In-Reply-To: <1141953732.182782.137070@j33g2000cwa.googlegroups.com> References: <1141948280.743094.217230@j33g2000cwa.googlegroups.com> <1141953732.182782.137070@j33g2000cwa.googlegroups.com> Message-ID: <4411120b$1@nntp0.pdx.net> rh0dium wrote: > Basically there are multiple combinatories here - I was hoping someone > could point me to a general approach. Writing the actual funtion is > not necessary - as you pointed out I can certainly do that. Here is my > problem - I did exactly as you and said OK I can > > if Foundry==None and Process==None: > > elif Foundy==None and Process!=None: > > elif Foundy!=None and Process==None: > > elif Foundy!=None and Process!=None: > > But this seems very ugly... And if I want to do this for the three > areas, it seems very repetitive. I was looking for a better way to > break this down which is reusable. First, use identity comparisons with None. Second, I'd do it like this: if Foundry is None: # common ~Foundry stuff if Process is None: pass # ~F & ~P stuff else: pass # ~F & P stuff # common ~Foundry stuff needing Process resolved else: # common Foundry stuff if Process is None: pass # F & ~P stuff else: pass # F & P stuff # common ~Foundry stuff needing Process resolved Unless there is more Process / ~Process common work, in which case re-nest. Don't be scared to write "the obvious" in Python. Second, once it grows to over two, think about doing things by cases: def AllTrue(Foundry, Process, Vendor): print 'Triple', (Foundry, Process, Vendor) def NoVendor(Foundry, Process, Vendor): print 'Pair', (Foundry, Process) ... def Nothing(Foundry, Process, Vendor): print 'Nada' behavior = {0: AllTrue, 1:NoVendor, 2:NoProcess, 3: OnlyFoundry, 4: NoFoundry, 5:OnlyProcess, 6:OnlyVendor, 7: Nothing} def dispatch(f, p, v): return behavior[((f is None) * 2 + (p is None)) * 2 + (v is None)](f, p, v) ... dispatch('Intel', 'Silicon', None) --Scott David Daniels scott.daniels at acm.org From doug at localhost.localdomain Fri Mar 17 08:15:50 2006 From: doug at localhost.localdomain (Doug) Date: Fri, 17 Mar 2006 13:15:50 GMT Subject: Python / glade fundamentals References: Message-ID: OK, I have solved the problem. The reference was a help. The clue is that the events may not get passed through the parent. For reference here is the code that worked. It's good to finally get the basics working. Doug import gtk import gtk.glade def key_press(widget,event): print "keypress" xml = gtk.glade.XML('pgtest.glade') widget = xml.get_widget('drawingarea1') xml.signal_autoconnect({ "on_page_key_press_event": key_press, "on_page_destroy_event": gtk.main_quit }) gtk.main() =======file: pgtest.glade======= True PGtestWindow GTK_WINDOW_TOPLEVEL GTK_WIN_POS_NONE False 640 480 True True True False False GDK_WINDOW_TYPE_HINT_NORMAL GDK_GRAVITY_NORTH_WEST True From theller at python.net Tue Mar 14 09:17:29 2006 From: theller at python.net (Thomas Heller) Date: Tue, 14 Mar 2006 15:17:29 +0100 Subject: Trace dynamically compiled code? In-Reply-To: <6A65F4A4-DC66-46E2-B2EB-3BB50DCE2856@leafe.com> References: <6A65F4A4-DC66-46E2-B2EB-3BB50DCE2856@leafe.com> Message-ID: Ed Leafe wrote: > Hi, > > Thanks to the help of many on this list, I've been able to take code > that is created by the user in my app and add it to an object as an > instance method. The technique used is roughly: > > nm = "myMethod" > code = """def myMethod(self): > print "Line 1" > print "My Value is %s" % self.Value > return > """ > compCode = compile(code, "", "exec") > exec compCode > exec "self.%s = %s.__get__(self)" % (nm, nm) > > This is working great, but now I'm wondering if there is a way to > enable pdb tracing of the code as it executes? When tracing "normal" > code, pdb will show you the name of the script being executed, the > line number and the source code for the line about to be executed. > But when stepping through code compiled dynamically as above, the > current line's source code is not available to pdb, and thus does not > display. > > Does anyone know a way to compile the dynamic code so that pdb can > 'see' the source? I suppose I could write it all out to a bunch of > temp files, but that would be terribly messy. Are there any neater > solutions? You coud monkey-patch the getline function in the linecache module, so that it is able to find your dynamically generated code. IMO that is what pdb uses.c Thomas From apardon at forel.vub.ac.be Thu Mar 30 08:50:17 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 30 Mar 2006 13:50:17 GMT Subject: any() and all() on empty list? References: <442B9AF7.2010407@REMOVEMEcyber.com.au> <7xu09gicko.fsf@ruckus.brouhaha.com> <442BAAA5.8010009@REMOVEMEcyber.com.au> Message-ID: Op 2006-03-30, Steven D'Aprano schreef : > Paul Rubin wrote: > >> Steven D'Aprano writes: >> >>>Think of it this way: if all(seq) is true, shouldn't it be the case >>>that you can point to a specific element in seq that is true? >> >> >> No, all(seq) is true if you can't point to a specific element in seq >> that's false. > > No, all(seq) is true if every element in seq is true. > Surely that's a more intuitive definition than your > definition by what you can't do. > > The question that needs to be answered is, what if > there are no elements at all? That's an arbitrary > decision. Like the question "what is 0**0?" in > mathematics, some answers are more useful than others. > I can respect that practical answer -- but it isn't the > *only* answer. > > (For those who don't see why 0**0 is problematic, 0**x > is equal to 0 for all x, and x**0 is equal to 1 for all > x, so what do you do for 0**0?) > > Here's another way of looking at the problem: > > all(flying elephants which are pink) => true > all(flying elephants which are not pink) => true > > So, these flying elephants -- are they pink or not? They are both. -- Antoon Pardon From lists at elehack.net Thu Mar 2 16:18:11 2006 From: lists at elehack.net (Michael Ekstrand) Date: Thu, 2 Mar 2006 15:18:11 -0600 Subject: how do you move to a new line in your text editor? In-Reply-To: <%ZGNf.1711$No6.40016@news.tufts.edu> References: <%ZGNf.1711$No6.40016@news.tufts.edu> Message-ID: <20060302151811.0b1ce977.lists@elehack.net> On Thu, 02 Mar 2006 18:39:55 GMT John Salerno wrote: > But I read in the PEP that spaces are recommended over tabs. If this is > the case, it would involve pressing backspace 4 times (or 8, etc.) to > get back to column 1. > > So I'm wondering, how do you all handle moving around in your code in > cases like this? Is there some sort of consistency to these things that > you can write rules for your text editor to know when to outdent? It > doesn't seem like you can do this reliably, though. I use Vim, use spaces, and have no problems. It has a shorttabstop option, which causes backspace to backspace to the preceding multiple of spaces when the curser is after a set of spaces at the beginning of the line. It feels like I'm using tabs, but I'm not. Also, there's some Python indenting/folding macros I picked up from Vim Online (don't remember where exactly), that provide an indent/outdent pair of key mappings, which also work perfectly with my usage of 4 spaces. - Michael -- mouse, n: a device for pointing at the xterm in which you want to type. -- Fortune From eoinrogers at gmail.com Wed Mar 8 10:35:58 2006 From: eoinrogers at gmail.com (Byte) Date: 8 Mar 2006 07:35:58 -0800 Subject: Interfacing with the command line Message-ID: <1141832158.003219.209260@j33g2000cwa.googlegroups.com> I know its possible to acsess Python via the command line, but can I do the opposite and acsess the command line via Python? For example, can I write a script that will enter $ firefox on the command line, opening Firefox for me? Thanks in advance, -- /usr/bin/byte From dananrg at yahoo.com Wed Mar 1 14:51:50 2006 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: 1 Mar 2006 11:51:50 -0800 Subject: Best python module for Oracle, but portable to other RDBMSes In-Reply-To: References: <1140818561.458171.237850@p10g2000cwp.googlegroups.com> <1140826717.186051.261430@i39g2000cwa.googlegroups.com> Message-ID: <1141242710.730153.279490@z34g2000cwc.googlegroups.com> Thanks Gerhard and Magnus. Magnus, thanks for the references. I will follow up on those. I was messing around with the native ODBC module you mentioned (I am using Python in a Win32 environment), e.g: import dbi, odbc ...and it seems to meet my needs. The only issue I've had so far is retrieving data from Oracle when an integer has been defined like: number(p) [same thing as number(p,0) evidently This is from a database I didn't design and can't change. The problem is that the ODBC module suffixes an "L" to any integer returned that was defined as data type number(p). For example, an integer stored as: 56 will be returned as 56L. Numbers that were specified as number(p,s), the module has no problem with. Anyone know why this would happen? Incidentally, performance isn't an issue for this particular use case. From http Fri Mar 31 23:33:46 2006 From: http (Paul Rubin) Date: 31 Mar 2006 20:33:46 -0800 Subject: Pickle or Mysql References: <1143864315.283697.20970@v46g2000cwv.googlegroups.com> Message-ID: <7xhd5drk2d.fsf@ruckus.brouhaha.com> amaltasb at gmail.com writes: > Can I use Pickle to store about 500,000 key value pairs.. or should I > use mySql. Which one is best for performance, as the key value pair > increases. That's an awfully large pickle. Maybe you want shelve. If there are frequent updates, multiple clients, etc., then yes, use a database like mysql. From andreas at nospam.openrts.org Fri Mar 10 16:51:19 2006 From: andreas at nospam.openrts.org (Andreas R.) Date: Fri, 10 Mar 2006 22:51:19 +0100 Subject: XML international characters Message-ID: Hello, When parsing XML documents containing international characters, such as the Norwegian characters ?, ?, ?, I get an exception in Python's SAX module. What is the correct way to parse such characters in Python? I've searched for methods to somehow escape the characters, without any luck so far. Thanks in advance, Andreas www.openrts.org - Python RTS game From fumana at lambrate.inaf.it Fri Mar 10 04:42:53 2006 From: fumana at lambrate.inaf.it (Marco Fumana) Date: Fri, 10 Mar 2006 10:42:53 +0100 Subject: API/C memory mananegemnt problem Message-ID: <200603101042.53748.fumana@mi.iasf.cnr.it> Thank for your help. I have try to follow your suggestion but I seem to fail. Now my C-module (call it C_Core) code is: *********************************************** /* create_list function */ int size=10000000; output=(double *) calloc(size, sizeof(double)); py_output=PyList_New(0); for(i=0; i References: <1142450161.536293.256580@i40g2000cwc.googlegroups.com> Message-ID: <1142452183.751660.69990@i39g2000cwa.googlegroups.com> Yeah, thats a good approach. I have been fiddling around to implement that feature in elements.py and RTF specification from msdn However, I have not been successful thus far. To answer my first question: > 1. do an align right of contents inside a cell Its not possible by speficying alignment in the Cell instance However, if you really want this feature then create a Paragraph and then set alignment=2 for the ParagraphPropertySet object Snippet: p = Paragraph( ss.ParagraphStyles.Normal, ParagraphPS(alignment=2) ) p.append() c1 = Cell(p) From lists at fabis-site.net Wed Mar 1 10:38:23 2006 From: lists at fabis-site.net (Fabian Steiner) Date: Wed, 01 Mar 2006 16:38:23 +0100 Subject: Printing a file In-Reply-To: References: Message-ID: Hi! Thank you so far, but now I got stuck again :-/ Jeremy Sanders wrote: > QPrinter is easy to use. You just draw to the page the same way as you talk > to the screen with a QPainter. > > prnt = qt.QPrinter() > # you can also vary options like colour, doc name, dpi here > > # display dialog box to user (you can actually leave this out) > if prnt.setup(): > painter = qt.QPainter() > painter.begin(printer) > # do stuff to draw to painter > painter.end(printer) > # do this between each page > printer.newPage() This is what I have so far: app = QApplication(sys.argv) printer = QPrinter(QPrinter.PrinterResolution) if printer.setup(): printer.setPageSize(printer.A4) painter = QPainter(printer) metrics = QPaintDeviceMetrics(painter.device()) marginHeight = 6 marginWidth = 8 body = QRect(marginWidth, marginHeight, metrics.widthMM() - 2 * marginWidth, metrics.heightMM() - 2 * marginHeight) painter.drawRect(body) painter.end() Doing so I hoped to get a rectangle which is as big as an A4 paper (with a small border), but unfortunately it is much smaller. Moreover, I ask myself whether it is necessary that in order to write text on the paper, I always have to pass the proper x, y values to QPainter.drawText(). Isn't there any other possibility? How do I get these values? Thanks in advance, Fabian Steiner From no-spam at no-spam-no-spam.com Mon Mar 27 10:59:04 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Mon, 27 Mar 2006 17:59:04 +0200 Subject: encode short string as filename (unix/windows) Message-ID: want to encode/decode an arbitrary short 8-bit string as save filename. is there a good already builtin encoding to do this (without too much inflation) ? or re.sub expression? or which characters are not allowed in filenames on typical OS? robert From paddy3118 at netscape.net Sat Mar 18 17:06:03 2006 From: paddy3118 at netscape.net (Paddy) Date: 18 Mar 2006 14:06:03 -0800 Subject: filter list fast In-Reply-To: <1142718311.059902.140740@p10g2000cwp.googlegroups.com> References: <1142675680.468064.167930@v46g2000cwv.googlegroups.com> <1142689630.989957.104200@p10g2000cwp.googlegroups.com> <1142702667.625459.151730@i39g2000cwa.googlegroups.com> <1142718311.059902.140740@p10g2000cwp.googlegroups.com> Message-ID: <1142719563.708781.76610@i39g2000cwa.googlegroups.com> Thanks. From gau.tai at gmail.com Fri Mar 10 15:48:14 2006 From: gau.tai at gmail.com (gau.tai at gmail.com) Date: 10 Mar 2006 12:48:14 -0800 Subject: MS Access db (mdb): viewing table attributes In-Reply-To: <1142023136.317554.144900@u72g2000cwu.googlegroups.com> References: <1142013201.717227.282050@i39g2000cwa.googlegroups.com> <1142015135.286529.209020@e56g2000cwe.googlegroups.com> <1142015868.754519.259200@e56g2000cwe.googlegroups.com> <1142023136.317554.144900@u72g2000cwu.googlegroups.com> Message-ID: <1142023694.024993.109730@j33g2000cwa.googlegroups.com> That would be fine for me to switch to mxodbc, I've used it before and it worked fine. But if I switch, do you know how I can get the column names from the table? Maybe I'm not being clear with my question here. I'm going to try again.... here's a table (it's in access): === tablename = mytable === id | user | pass | access privileges <-- these are the column names I want ================================ 0 bob 12345 admin/full 1 sam 53432 power user 4 mike 43234 guest I know how to connect to the database. I know how to get the table names. How can I get the names of the columns for each table?? From mahs at telcopartners.com Wed Mar 22 16:34:11 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Wed, 22 Mar 2006 13:34:11 -0800 Subject: Per instance descriptors ? In-Reply-To: <4421b54d$0$21546$626a54ce@news.free.fr> References: <44211ee8$0$7890$636a55ce@news.free.fr> <1143038744.159609.104460@g10g2000cwb.googlegroups.com> <44216fc5$0$26190$626a54ce@news.free.fr> <4421b54d$0$21546$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Michael Spencer a ?crit : >> I may be missing the subtlety of what you're up to, but why is >> overriding __getattribute__ more desirable than simply defining the >> descriptor in a subclass? > > The code snippet I gave as an example was not supposed to reflect how I > effectively mean to use per-instance descriptors, it was just a kind of > Minimal Working Code (tm). The real life code is about 500 LOC, and > explaining the whole thing would take far too long. Also, as I said, > this is mostly syntactic sugar - there are simpler, less 'hackish' (but > also less elegant) solutions to the actual 'problem'.So, to answer your > question, no, subclassing would not be a solution - I'd almost need a > subclass per controller function, which would reintroduce the > boilerplate I'm trying to get rid of. > > BTW, there may be other use case for per-instance descriptors... Agreed. Per-instance descriptors could be interesting (that's why the subject line caught my attention). But your solution involves a custom __getattribute__ in the class, which I would always avoid if possible (and I gather you're uneasy about it too). Here, I don't see why that's better than having a descriptor in the class and, if it needs per-instance behavior, then make it dependent on something provided by the instance. e.g., class DummyDescriptor1(object): def __get__(self, obj, objtype=None): if isinstance(obj, objtype): return obj.foo.__get__(obj) else: return self class MyClass4(object): baaz = DummyDescriptor1() def __init__(self, foo, bar = None): self.foo = foo self.bar = bar >>> mc4 = MyClass4(lambda self: self.bar, "I'm bar") >>> mc4.baaz >>> mc4.baaz() "I'm bar" >>> mc5 = MyClass4(lambda self: "I ignore bar", "I'm another bar") >>> mc5.baaz() "I ignore bar" >>> Python > is so dynamic that you can almost use it like a prototype-based language. > > Almost, yes. Michael From reply.in.the.newsgroup at my.address.is.invalid Sat Mar 4 07:53:43 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 04 Mar 2006 13:53:43 +0100 Subject: How to except the unexpected? References: <1oui02pfcnnk8ol44uubqrna3v6huikokc@4ax.com> <8764mu8ki5.fsf@ieee.org> Message-ID: <2s2j02h6ui4b71u635kjicevnkudoa0u1u@4ax.com> Jorge Godoy: >Rene Pijlman: >> my app was surprised by an >> httplib.InvalidURL since I hadn't noticed this could be raised by >> robotparser (this is undocumented). > >It isn't undocumented in my module. From 'pydoc httplib': That's cheating: pydoc is reading the source :-) What I meant was, I'm calling robotparser, and there's no mention of exceptions on http://docs.python.org/lib/module-robotparser.html -- Ren? Pijlman From aleaxit at yahoo.com Sat Mar 4 12:15:41 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Mar 2006 09:15:41 -0800 Subject: Random Prime Generator/Modular Arithmetic References: <1141487100.450422.306010@v46g2000cwv.googlegroups.com> Message-ID: <1hbo45c.6kg75cbrxcaiN%aleaxit@yahoo.com> Tuvas wrote: ... > to make sure. For simpler than going to the website, I used the ranint I assume you mean random.randint here. > function to pick a random prime number, then ran it through the miller > rabin primality test. It's a probabalistic test, which means it isn't > full proof, but there's still less than 1 in a million of giving a Miller-Rabin is not the problem -- rather, random.randint might be... it makes no claims to be cryptographically strong, in either the current Mersenne implementation or the previous Wichman-Hill one. Could you maybe use /dev/random or the like? Cfr for an introduction to the subject. (For speed, you may want to look into gmpy.sf.net, but that's quite a separate issue from the strength of your random numbers). Alex From robert.h.boyd at gmail.com Wed Mar 1 08:47:49 2006 From: robert.h.boyd at gmail.com (Robert Boyd) Date: Wed, 1 Mar 2006 08:47:49 -0500 Subject: Is Python a Zen language? In-Reply-To: <7xoe0vhwmi.fsf@ruckus.brouhaha.com> References: <1140876556.080086.252390@e56g2000cwe.googlegroups.com> <1140878147.541074.233540@i40g2000cwc.googlegroups.com> <1140879469.853398.322850@i40g2000cwc.googlegroups.com> <1140903119.580735.108440@e56g2000cwe.googlegroups.com> <7xoe0vhwmi.fsf@ruckus.brouhaha.com> Message-ID: On 25 Feb 2006 15:00:37 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Kay Schluehr" writes: > > I have at times the impression that many people who talk about Zen > > philosophy confuse it with some home brewn mixture of platonism with > > its transgressive move towards the true reality, a stoic hedonism of > > contemplation and the taoistic being-in-doing. Zen on the other side is > > more radical: if you erase yourself there is no-one "who" is in the > > flow but chances are that you and the computer over there are the same > > thing. > > QOTW or something. > -- How about, cue the "Philosophers' Song"? From aaronwmail-usenet at yahoo.com Tue Mar 14 14:19:04 2006 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 14 Mar 2006 11:19:04 -0800 Subject: Tried Ruby (or, "what Python *really* needs" or "perldoc!") In-Reply-To: References: <1142355126.757569.42160@i40g2000cwc.googlegroups.com> Message-ID: <1142363944.661130.301150@i39g2000cwa.googlegroups.com> I agree that more progress is needed on the Python documentation front. For example if you look at the "codecs" module documentation there is no hint of what a codec is anywhere that I can see. Also the distinction between an "encoder" and a "decoder" is not explained. Even though I've used it many times and understand it, I still find myself using the interactive interpreter to make sure I'm sending the bytes in the right direction... Perhaps some faqwiz/wiki-like tool to allow the broader community to propose documentation enhancements would be useful? -- Aaron Watters === "I know what it's like to put food on my family." G.W.Bush From joel.hedlund at gmail.com Mon Mar 27 07:52:46 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Mon, 27 Mar 2006 14:52:46 +0200 Subject: Difference between 'is' and '==' In-Reply-To: <4427d287$0$38669$edfadb0f@dread12.news.tele.dk> References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <4427d287$0$38669$edfadb0f@dread12.news.tele.dk> Message-ID: > "is" is like id(obj1) == id(obj2) > (Think of id as memory adresses.) Which means that "is" comparisons in general will be faster than == comparisons. According to PEP8 (python programming style guidelines) you should use 'is' when comparing to singletons like None. I take this to also include constants and such. That allows us to take short cuts through known terrain, such as in the massive_computations function below: -------------------------------------------------------------- import time class LotsOfData(object): def __init__(self, *data): self.data = data def __eq__(self, o): time.sleep(2) # time consuming computations... return self.data == o.data KNOWN_DATA = LotsOfData(1,2) same_data = KNOWN_DATA equal_data = LotsOfData(1,2) other_data = LotsOfData(2,3) def massive_computations(data = KNOWN_DATA): if data is KNOWN_DATA: return "very quick answer" elif data == KNOWN_DATA: return "quick answer" else: time.sleep(10) # time consuming computations... return "slow answer" print "Here we go!" print massive_computations() print massive_computations(same_data) print massive_computations(equal_data) print massive_computations(other_data) print "Done." -------------------------------------------------------------- Cheers, Joel From s.lipnevich at gmail.com Sun Mar 26 18:14:30 2006 From: s.lipnevich at gmail.com (s.lipnevich at gmail.com) Date: 26 Mar 2006 15:14:30 -0800 Subject: "For" loop and list comprehension similarity References: <1143396590.320442.94920@t31g2000cwb.googlegroups.com> Message-ID: <1143414870.330921.305890@j33g2000cwa.googlegroups.com> > Why not combine the two: I guess because (at least in source code) you're doing a loop twice :-). I don't know what a compiler would do. I think though that the "for i in c if test:" construct is more readable and maybe can even be better optimized. Thanks! Sergey. From reply.in.the.newsgroup at my.address.is.invalid Tue Mar 28 13:36:45 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 28 Mar 2006 20:36:45 +0200 Subject: trying to use popen2() to communicate with C program References: Message-ID: <2h0j22dsgq2vf42bmoqrcj0444e4ab097l@4ax.com> I. Myself: >I can't get this to work With what versions of what software on what platform? -- Ren? Pijlman From erniedude at gmail.com Wed Mar 29 12:49:01 2006 From: erniedude at gmail.com (Ernesto) Date: 29 Mar 2006 09:49:01 -0800 Subject: Terminating a subprocess question In-Reply-To: <48vsl1Fmc3tkU1@uni-berlin.de> References: <1143649900.667952.15410@t31g2000cwb.googlegroups.com> <48vsl1Fmc3tkU1@uni-berlin.de> Message-ID: <1143654541.198515.62520@z34g2000cwc.googlegroups.com> Diez B. Roggisch wrote: > Ernesto wrote: > > > I'm opening a telnet session with the subprocess call below. I then > > wait ten seconds and attempt to terminate the telnet window I created. > > Unfortuantely, the telnet window remains after the 'TerminateProcess" > > call below. This software works great for opening an executable > > directly (i.e. Handle = subprocess.Popen("myProgram.exe), but here I'm > > using the Windows 'start' command inside, which I think has an effect. > > > > > > Is there another way I can force termination of the telnet session I > > create ? > > Maybe using the module telnetlib instead? > > Diez oh ok great ! But how would I create a log file. Couldn't seem to find that here: http://python.active-venture.com/lib/telnet-objects.html http://pydoc.org/1.6/telnetlib.html Plus, everytime, I tried to use the read_all object, my program crashed pretty hard... tn = telnetlib.Telnet("localhost",6000) print tn.read_all() # CRASH From joel.hedlund at gmail.com Fri Mar 17 08:20:01 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Fri, 17 Mar 2006 14:20:01 +0100 Subject: Tried Ruby (or, "what Python *really* needs" or "perldoc!") In-Reply-To: References: <1142355126.757569.42160@i40g2000cwc.googlegroups.com> <1142397587.151040.35450@j33g2000cwa.googlegroups.com> <1142434139.499666.281590@v46g2000cwv.googlegroups.com> <1142455170.389577.320760@j52g2000cwj.googlegroups.com> Message-ID: >>This "release" is as alpha as alpha gets. It's so alpha it >>actually loops back around to zeta -- but it's a start, and I >>think it's exactly what the Python community needs. > > > Not to pick nits, but that should actually be "... so alpha that it actually > loops back around to *OMEGA*." > I think he's using extended Greek++. That got seriously big around the late B.C's. /Joel Sorry for this garbage post, btw... Couldn't help myself... :-) From piet at cs.uu.nl Wed Mar 22 04:09:29 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 22 Mar 2006 10:09:29 +0100 Subject: Which GUI toolkit is THE best? References: <441172c2$1@news1.ethz.ch> <1jk98ti5l75jq$.185esrz0xojp3$.dlg@40tude.net> Message-ID: >>>>> Michael Ekstrand (ME) wrote: >ME> I've used both wxPython and PyGTK. I find wxPython to be horribly >ME> un-pythonic; combining that some problems on the Mac, and some >ME> other installation/environment issues, I ditched it for PyGTK. But AFAIK GTK doesn't have a native implementation on the Mac, only X11. At least not in a stable version. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From timothy.grant at gmail.com Fri Mar 31 22:13:29 2006 From: timothy.grant at gmail.com (Timothy Grant) Date: Fri, 31 Mar 2006 19:13:29 -0800 Subject: smtplib "authentication required" error In-Reply-To: <1143858027.337885.24650@j33g2000cwa.googlegroups.com> References: <1143858027.337885.24650@j33g2000cwa.googlegroups.com> Message-ID: On 31 Mar 2006 18:20:27 -0800, carl.reimann at gmail.com wrote: > In using a simple smtp routine: > > # begin example > >>> import smtplib > >>> server = smtplib.SMTP('outgoing.verizon.net') > >>> server.sendmail('my at address.net', 'another at address.net', > """To: another at address.net > From: my at address.net > Subject: Shakespeare Quote > > Tis like the breath of an unfeed lawyer... > """) > >>> server.quit() > # end example > > I find the following error: > > raise SMTPSenderRefused(code, resp, from_addr) > smtplib.SMTPSenderRefused: (550, '5.7.1 Authentication Required', > 'myuserid at verizon.net') > > > I have attempted to incorporate into the interactive session: > > server.login = ('userid', 'password') # the same ones I use in my > email program I had some trouble with this not too long ago. I don't know what kind of authentication your mail server requires, but to send through gmail I had to do the following. s = smtplib.SMTP('smtp.gmail.com') s.set_debuglevel(1) s.ehlo() s.starttls() s.ehlo() s.login('foo', 'bar') s.sendmail(from_address, to_addresses, msg) s.close() Hope that helps. -- Stand Fast, tjg. From mike at mike.com Tue Mar 14 06:21:04 2006 From: mike at mike.com (Skipper) Date: Tue, 14 Mar 2006 11:21:04 GMT Subject: Please, I Have A Question before I get started References: <40l912h0aubfgai2en7n465ml9olg746h9@4ax.com> Message-ID: Well, thank you so much for taking the time to reply. I guess that about wraps up all my questions. You fucking putz On Mon, 13 Mar 2006 13:37:36 +0100, Sybren Stuvel wrote: >Skipper enlightened us with: >> I can not believe that there isn't a GUI programing tool that will >> allow me to build GUI apps > >There are plenty of them. > >> just like I use Dreamweaver to build a web page > >Which produces horrible HTML. > >Sybren From elpX at adsihqX.com Thu Mar 9 18:57:11 2006 From: elpX at adsihqX.com (Dr. Pastor) Date: Thu, 09 Mar 2006 23:57:11 GMT Subject: About printing in IDLE? Message-ID: Installed Python 2.4.2 on Windows XP. Activated IDLE. Loaded the following to the Edit window: --- print "hello world" for i in range(10): print i, print "Done" --- It prints as: 0 1 2 3 4 5 6 7 8 9 Done Should not Done be printed on a new line alone? Thanks for any guidance. From a_salnikov at yahoo.com Tue Mar 7 19:13:29 2006 From: a_salnikov at yahoo.com (Andy Salnikov) Date: Tue, 7 Mar 2006 16:13:29 -0800 Subject: Python advocacy in scientific computation References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> <1141583453.403143.189400@i40g2000cwc.googlegroups.com> <1141750637.180979.69890@j33g2000cwa.googlegroups.com> Message-ID: "Michael Tobis" wrote in message news:1141750637.180979.69890 at j33g2000cwa.googlegroups.com... >> Indentation >> makes all kinds of inlined code extremely clumsy or practically >> impossible >> in Python. > > This is the only sensible argument against the indentation thing I've > heard. Python squirms about being inlined in a presentation template. > Making a direct competitor to PHP in pure Python is problematic. > > While there are workarounds which are not hard to envision, it seems > like the right answer is not to inline small fragments of Python code > in HTML, which is probably the wrong approach for any serious work > anyway. This problem does, however, seem to interfere with adoption by > beginning web programmers, who may conceivably end up in PHP or perhaps > Perl Mason out of an ill-considered expedience. > > Why this should matter in this discussion, about scientific > programming, escapes me though. > > When you say "all kinds" of inlined code, do you have any other > examples besides HTML? > Makefiles is one example. Shell script containing snippet(s) of Python code is another one. At one time I also tried to make a simple "configuration file" engine based on Python for a big Framework used in one physics lab. Idea was to have a Python extension for that C++ framework and to configure the Framework from Python code, like: # Module means C++ Framework module, not Python Module1.param1 = "a string" Module2.paramX = [ 1, 2, 3 ] # etc., with all Python niceties. People who were using this Framework were all hard-core physicists, some of them knew Fortran, many were exposed to C++. There were few other "languages", some of them home-grown, used for different tasks, but none of these mentioned languages ever placed so much significance on the whitespaces. There were some big surprises for people when they discovered they can't arbitrary indent pieces of the above configuration files because it is all Python code. Add here space/tabs controversy if it is not enough yet to confuse poor physicist fellows :) I think that config file project was killed later in favor of less restrictive format (I left the lab before that, can't say for sure.) Andy. From fakeaddress at nowhere.org Sun Mar 5 20:47:46 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 06 Mar 2006 01:47:46 GMT Subject: Random Prime Generator/Modular Arithmetic In-Reply-To: <1141584746.985555.285570@j33g2000cwa.googlegroups.com> References: <1141487100.450422.306010@v46g2000cwv.googlegroups.com> <7x1wxhlx07.fsf@ruckus.brouhaha.com> <1141512951.983754.74980@i40g2000cwc.googlegroups.com> <1141584746.985555.285570@j33g2000cwa.googlegroups.com> Message-ID: <6xMOf.66118$PL5.60500@newssvr11.news.prodigy.com> Tuvas wrote: [...] > Actually, I did another test, and realized that it was indeed a bug in > the code. Yikes. Oh well, thanks for the help in identifying it! > > An example that would be alot easier is this: > >>>>Mod(16,561).is_strong_pseudo_prime() > > True Hmmm...my M-R tester disagrees... Ah, there's another bug in is_strong_pseudo_prime(). While your exponent 'x' is even, you do the test with x, not necessarily x/2. Incidentally, the lowest base for which 561 is strongly pseudo-prime is 50. -- --Bryan From dag_fjeld_edvardsen at hotmail.com Mon Mar 13 17:21:27 2006 From: dag_fjeld_edvardsen at hotmail.com (Dag Fjeld Edvardsen) Date: Mon, 13 Mar 2006 23:21:27 +0100 Subject: Python IDE: great headache.... References: <1142120002.912902.69630@i40g2000cwc.googlegroups.com> <4414099b@news.broadpark.no> Message-ID: <4415f0e3$1@news.broadpark.no> > What features exactly does it not have? Come to think of it, the only exception is probably that PyScripter (AFAIK) does not provide conditional pause. But I really like it. PyScripter is written in Delphi, my other favorite language :) -Dag From fredrik at pythonware.com Wed Mar 29 14:45:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 29 Mar 2006 21:45:26 +0200 Subject: Terminating a subprocess question References: <1143649900.667952.15410@t31g2000cwb.googlegroups.com><1143654541.198515.62520@z34g2000cwc.googlegroups.com> <1143659869.340205.289790@j33g2000cwa.googlegroups.com> Message-ID: Ernesto wrote: > > > tn = telnetlib.Telnet("localhost",6000) > > > print tn.read_all() > > > # CRASH > > > > that's an unusual error message. are you sure you didn't get a > > traceback? if so, what did it say? > > I was running it directly in a python shell. After the tn.read_all() > call, the python shell window freezes up, and I have to do a hard > termination of the shell. There is no traceback message, just a freeze. hmm. that hardly qualifies as a "CRASH"; rather, it's pretty much what you'd expect from a read_all call: >>> help(tn.read_all) Help on method read_all in module telnetlib: read_all(self) method of telnetlib.Telnet instance Read all data until EOF; block until connection closed. (note the "block until connection closed" part) what happens if you use a non-blocking method instead ? e.g. >>> help(tn.read_very_eager) Help on method read_very_eager in module telnetlib: read_very_eager(self) method of telnetlib.Telnet instance Read everything that's possible without blocking in I/O (eager). Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence. From aahz at pythoncraft.com Sat Mar 11 14:24:18 2006 From: aahz at pythoncraft.com (Aahz) Date: 11 Mar 2006 11:24:18 -0800 Subject: API/C memory mananegemnt problem References: <200603100919.29946.fumana@mi.iasf.cnr.it> <1142056998.489727.168570@e56g2000cwe.googlegroups.com> <1142060403.333298.86840@e56g2000cwe.googlegroups.com> <1hc18a8.1u0a6cx14wyhuhN%aleaxit@yahoo.com> Message-ID: In article <1hc18a8.1u0a6cx14wyhuhN%aleaxit at yahoo.com>, Alex Martelli wrote: > wrote: >> >> I think I understand the original statement now. What you are really >> saying is that there is a pool of Python float objects (which can, at >> different times, wrap different values) which can grow but never >> decrease in size. So the memory held by this pool is dictated by the >> maximum number of floats that have ever been simultaneously active >> (accessible). >> >> The same goes for integers. All the more reason to avoid range(.) and >> use xrange(.). > >Uh? The integers produced as you loop over xrange will be just immortal >as those that get into the list built by range, so why is int >immortality any reason to use one over the other? Because unless you save the ints produced by xrange(), you're reusing slots in the free list as you go through the loop, whereas range() chews up a gob of memory that will never get released even if you never otherwise use all the ints it produces. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From lycka at carmen.se Thu Mar 16 09:37:48 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 16 Mar 2006 15:37:48 +0100 Subject: python debugging question In-Reply-To: <1141853024.196597.49410@j52g2000cwj.googlegroups.com> References: <1141853024.196597.49410@j52g2000cwj.googlegroups.com> Message-ID: diffuser78 at gmail.com wrote: > I am a python newbie. I have writen some 500 lines of code. There are 4 > classes and in all 5 files. > > Now, I am trying to run the program. I am getting wrong values for the > simulation results. If you first write 500 lines of code, and *then* try to run it, it seems you are using a development approach suitable in the 1960's when running a program meant handing a stack of punch cards to a computer operator in a white coat, and then getting the result of the run the next day (if you're lucky). I was taught to write like this as recently as in the late 80's when I was in universtity, but today I typically run my code every ten minutes or so. It's rare that I run the code I work on less frequently than every thirty minutes. In my experience, my current way of developing software leads to higher productivity, better quality and much better predictability in regards to both development time and software performance and features. The way to achieve this is to use lots of automated tests and a development time where you learn to work in small increments. Martin Fowler's book "Refactoring" is a good guide for this, and Python is a very good language to use for this kind of development. Perhaps this might be useful? http://www.thinkware.se/cgi-bin/thinki.cgi/SoftwareTestingWithPython http://thinkware.se/epc2004test/log.html From cfc at shell01.TheWorld.com Mon Mar 27 15:01:35 2006 From: cfc at shell01.TheWorld.com (Chris F Clark) Date: 27 Mar 2006 15:01:35 -0500 Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1143024937.827420.104100@i39g2000cwa.googlegroups.com> <20060322141400.1A00.1.NOFFLE@dthierbach.news.arcor.de> <1143110872.284192.325230@u72g2000cwu.googlegroups.com> <20060323134326.C29.0.NOFFLE@dthierbach.news.arcor.de> <1143134775.887696.5000@z34g2000cwc.googlegroups.com> <20060323212800.79D.0.NOFFLE@dthierbach.news.arcor.de> <1143193333.963153.23850@g10g2000cwb.googlegroups.com> <20060324105346.10AF.0.NOFFLE@dthierbach.news.arcor.de> <1143221565.921043.312080@z34g2000cwc.googlegroups.com> <20060325092954.60C.0.NOFFLE@dthierbach.news.arcor.de> <1143483991.216107.143010@g10g2000cwb.googlegroups.com> Message-ID: Yes, there is literature on the generating side of the regular expression/FSM model. In fact, the matching problem and the generating problems are exactly equivalent. A slight variation of the definition of how a matcher works, turns it into a generator and vice versa. To directly generate (rather than match) from an FSM, one simply does a walk (e.g. depth first search or breath first search) over the machine writing out (rather than matching) the symbols used as labels. Thus, all the theorems about matching apply to generating and also in reverse. You can see this to some extent form the problem posed. If one generates Sigma* and subtracts out the elements from some regular language (say by matching them), that is exactly equivalent (in strings generated) to generating the complement of the regular language. In fact, it is quite easy (with the correct regular expression tool, i.e. one that handles regular expression differences) to take the problems posed and generate provably minimal (i.e. provably maximally efficient) generation (or matching) programs as FSMs. The provably minimal FSM won't go down any paths that don't have some sequence that generates an "accept" value. It is worth noting the regular languages are closed under the difference operator, so that resulting language from substracting one regular expression from another is still a regular language, which can be used to prove that the machine is minimal. Therefore, while the output can be exponentially larger than the input, one should expect that implementations should be able to generate the output in linear time (relative to the size of the output), since FSMs run in linear time relative to the string they are processing (whether generating or matching). Under a reasonable model of computation, one cannot do better than linear in the size of string processed. I'm sure if you asked under comp.theory, you would get tons of other relevant facts from someone who understands automata theory better than I. Note, if one does ask there, one should correct the notation. The "*" symbol was used as in globbing, not as commonly used in regular expressions. The notation ".*" (as someone corrected in one of their replies) is the normal notation for what the original poster wanted by "*". 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 wkehowski at cox.net Sat Mar 18 11:08:06 2006 From: wkehowski at cox.net (wkehowski at cox.net) Date: 18 Mar 2006 08:08:06 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <8764medlhm.fsf@qrnik.zagroda> <1142556358.098924.59180@e56g2000cwe.googlegroups.com> <1142559980.525680.282250@u72g2000cwu.googlegroups.com> Message-ID: <1142698086.042262.161710@z34g2000cwc.googlegroups.com> When I run this I get through ghc I get C:\Documents and Settings\User\My Documents\wildcard>ghc "./wc-zielonka.hs" compilation IS NOT required C:/Languages/ghc/ghc-6.4.1/libHSrts.a(Main.o)(.text+0x1d):Main.c: undefined refe rence to `__stginit_ZCMain' C:/Languages/ghc/ghc-6.4.1/libHSrts.a(Main.o)(.text+0x43):Main.c: undefined refe rence to `ZCMain_main_closure' collect2: ld returned 1 exit status Unless there's a command line option I'm missing? From fuzzyman at gmail.com Sun Mar 26 14:30:10 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 26 Mar 2006 11:30:10 -0800 Subject: [ANN] Firedrop 0.2.0 - The Python Blog Client Message-ID: <1143401410.698335.63340@g10g2000cwb.googlegroups.com> It has finally happened, the release of `Firedrop 0.2.0 `_. The impatient can download the new release here : `Firedrop 0.2.0 (1.3mb) `_ .. note:: The first time you run version 0.2.0 it will convert your weblog config file to the new format. **Firedrop2** is the Python blog client with a host of features. These include : * RSS feed generation * Categories * Automatic archive generation * A powerful set of plugins, including spell checker and emailer * Entries can be made in text, HTML, ReST, textile, sextile or markdown markup * HTML templating system and macros for all sorts of tricks * Built in FTP capability for uploading your blog to a server * Because it's written in Python, it is easy to extend Firedrop or create new plugins for it This new release has been made possible by the hard work of `Stewart Midwinter `_. The changes and new features include : * Firedrop will now start up by opening a default site. * You can set the default site using the GUI. * Main file name changed to ``firedrop.pyw`` * `ConfigObj `_ is now used to edit all the config files. * Full support for all style elements (e.g. underline, bold) in four major markup formats: ReST, Sextile, Textile, Markdown (plus HTML). * New entries are created in a separate dialog that takes care of the markup. * Links are available to websites for the markup styles. * You can reset the app to a null site, and/or delete all entries. * You can force a full build of your site, or just update your site. * You can now create sites serving Article Collections or Items Lists (e.g. FAQs) in addition to Weblogs. * Firedrop2 now runs on Mac OS X and Linux in addition to Windows. * You can view logfile contents using the GUI. * Documentation has been updated to reflect these changes. There is a roadmap for future releases on the `Firedrop2 Trac Site `_. From cdkrug at aol.com Sun Mar 19 07:41:59 2006 From: cdkrug at aol.com (Charles Krug) Date: Sun, 19 Mar 2006 06:41:59 -0600 Subject: Want to re-pack() a Frame displaying a collection Message-ID: List, I'd like to do the following with Tkinter's Frame() object: 1. Display a collection of pack()-able objects. Easy. Done. I hold the objects in a dictionary, mostly so that the owning program can refer to them uniformly. 2. Whenever the collection is added to or deleted from, re-pack() the owning object. Will this happen automatically simply whenever I add or delete from the object's __dict__, or do I need to add to __setattr__ and __delattr__ to detect when the user has added or removed an object? Thanks Not Quite Related: I'm doing a lot of displaying of (Label, Entry) pairs so I've another subclass of Frame() that simplifies that action for me. These are items from a collection that's created at runtime where the labels aren't known in advance. Right now, I'm raising an exception if grid() or place() is called on the object. Eventually, what I'd like to do is flesh out the grid() and place() methods so that the Label and Entry are placed in what I think are sensible default positions reletive to the desired placement. With grid(), how do I determine my current column and row in the case when grid() is invoked without arguments? With place() . .pretty much the same song. I need to determine my position so that I can Do The Right Thing (or at least the expected thing). Thanks From vincenzo.cacciatore at gmail.com Wed Mar 15 10:44:13 2006 From: vincenzo.cacciatore at gmail.com (LabWINC) Date: 15 Mar 2006 07:44:13 -0800 Subject: FIR filtering In-Reply-To: References: <1142428703.224948.317700@u72g2000cwu.googlegroups.com> <1142431475.577039.286470@e56g2000cwe.googlegroups.com> Message-ID: <1142437453.065363.309720@i40g2000cwc.googlegroups.com> I'm interested in finding coefficient and implementig the filter as well. John's post is what i need. John Hunter wrote: > help scipy.filter (see FIR filter design below) How can i get the help like yours? If i type help scipy.filter it give me an error help scipy.filter File "", line 1 help scipy.filter ^ SyntaxError: invalid syntax I'm sorry but i'm new of python, Vincent From johnjsal at NOSPAMgmail.com Wed Mar 8 23:04:07 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Mar 2006 23:04:07 -0500 Subject: question about slicing with a step length In-Reply-To: <1141871828.993855.208580@v46g2000cwv.googlegroups.com> References: <440F848F.9000007@REMOVEMEcyber.com.au> <1141871828.993855.208580@v46g2000cwv.googlegroups.com> Message-ID: <2bSdncuWK7bmNJLZRVn-vA@rcn.net> Andr? wrote: > An extended slice of list x of length n in the form x[j:k:i] selects > every i-th element starting with and including the element at index j This makes it sound like the index of 10 should be inclusive. > When either index is missing or lies outside of the > list bounds, the minimum or maximum inclusive index is used > automatically. So does that mean that the example actually is wrong, and Python is compensating? I tried numbers[9:0:-2] and it returned the same value as if I had used 10 as the first index, so perhaps 10 shouldn't be there after all. From n.estner at gmx.de Mon Mar 27 11:14:07 2006 From: n.estner at gmx.de (nikie) Date: 27 Mar 2006 08:14:07 -0800 Subject: encode short string as filename (unix/windows) In-Reply-To: References: Message-ID: <1143476047.539096.250290@u72g2000cwu.googlegroups.com> > want to encode/decode an arbitrary short 8-bit string as save filename. > is there a good already builtin encoding to do this (without too much > inflation) ? or re.sub expression? > > or which characters are not allowed in filenames on typical OS? On Windows, / \ : * ? " < > | are forbidden, and the name can't be empty. Using urlsafe_b64encode/...decode should work on any platform. From duncan.booth at invalid.invalid Thu Mar 16 16:07:41 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Mar 2006 21:07:41 GMT Subject: Counting nested loop iterations References: <1142539976.631204.108260@u72g2000cwu.googlegroups.com> Message-ID: Derek Basch wrote: > index = 0 > for animal in zoo: > for color in animal: > index += 1 # assuming there is something more goes here... > You could do this, but it kind of depends what the loop *really* looks like: for index, color in enumerate(color for animal in zoo for color in animal): # the something more goes here. pass From python.list at tim.thechases.com Mon Mar 6 10:16:55 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 06 Mar 2006 09:16:55 -0600 Subject: help with loops In-Reply-To: <56BF0C633F594948B90E97636666DDF7A04C64@AMCW3VN503.amc.ds.af.mil> References: <56BF0C633F594948B90E97636666DDF7A04C64@AMCW3VN503.amc.ds.af.mil> Message-ID: <440C5267.2080200@tim.thechases.com> > I have two files and I want to pull out lines from file 2 > if certain conditions are found if file 1. Well, I'm not quite sure from your description of the problem if you want to compare every line in file1 against every line in file2, or if you just want to compare line1 of file1 with line1 of file2; line2 of file1 with line2 of file2... For the former, you'd use something like for line1 in file1.readlines(): list1 = line1.split(",") for line2 in file2.readlines(): list2 = line2.split(",") if (list1[3] == list2[6] and list1[4] == list2[8]): print line For the latter, you have to consider the case where one file is longer than the other, unless you happen to know that they're the same length. If they are, or you just want the min length of whichever is shorter, you could do something like for line1,line2 in zip(file1.readlines(), file2.readlines()): list1 = line1.split(",") list2 = line2.split(",") if list1[3] == list2[6] and list1[4] == list2[8]: print line Just a few thoughts you might try tinkering with to see if they do something close to what you want. -tkc From erniedude at gmail.com Thu Mar 23 18:36:24 2006 From: erniedude at gmail.com (Ernesto) Date: 23 Mar 2006 15:36:24 -0800 Subject: Terminating a subprocess '.exe' Message-ID: <1143156984.172363.246820@z34g2000cwc.googlegroups.com> I launch a Windows executable and wish to close it from Python. The code is below. Normally, my program waits for rib.exe to finish, but I'd like to be able to close it from python if possible. (I suppose if I was going to do this, I wouldn't use .wait() ) Any ideas ? # Launch a program without launching a whole new cmd prompt def launchWithoutConsole(command, args): """Launches 'command' windowless and waits until finished""" startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW return subprocess.Popen([command] + args, startupinfo=startupinfo).wait() ribHandle = launchWithoutConsole("rib.exe",["recovery"]) # Is there a way to close "rib.exe" using ribHandle ? From smitty_one_each at bigfoot.com Wed Mar 8 05:47:42 2006 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Wed, 08 Mar 2006 05:47:42 -0500 Subject: linux clipboard? References: <1141773655.057852.34430@j33g2000cwa.googlegroups.com> Message-ID: <87irqp6wmp.fsf@bigfoot.com> >>>>> "Rene" == Rene Pijlman writes: Rene> david.humpherys at gmail.com: >> how can i copy text to the linux clipboard? Rene> Linux is an operating system. It doesn't have a Rene> clipboard. The clipboard is provided by desktop frameworks, Rene> such as KDE or Gnome. Rene> -- Ren? Pijlman Actually, Linux is the kernel, and the full system is GNU/Linux, as RMS would hasten to point out. Isn't the clipboard a basic X component? However, for basic text, don't overlook the humble shell facilities like | , > , < , and >> R, Chris From peter_cole at comcast.net Wed Mar 22 15:10:08 2006 From: peter_cole at comcast.net (Peter Cole) Date: Wed, 22 Mar 2006 15:10:08 -0500 Subject: Trouble with generator as method In-Reply-To: References: Message-ID: Peter Otten wrote: > Peter Cole wrote: > >> I'm having difficulty understanding why this doesn't work: > >> import sys, new, inspect >> >> class T: >> def foo(self): >> yield 1 >> yield 2 >> yield 3 >> >> >> t = T() > > im = new.instancemethod(T.foo, t, T) > >> print t.foo >> print im > > # prints > # > > # > > > From the output you can see that both are equivalent bound methods. > >> print 't.foo().next() = %s' % t.foo().next() >> print 'im.next() = %s' % im.next() > > Yet you call t.foo() while you don't call im. > > Peter > Right, I've got it now, thanks. From fredrik at pythonware.com Mon Mar 13 11:55:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Mar 2006 17:55:34 +0100 Subject: Very, Very Green Python User References: <1142215118.291132.130490@e56g2000cwe.googlegroups.com> <44159fb4$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > > ... Is the Python debugger fairly stable? > Yes, but it is not massively featured. The "Pythonic" way is to > rarely use a debugger (test first and straightforward code should > lead to "shallow" bugs). Often for most of us judiciously placed > print statements suffice. combined with a modular design, so you can make sure that individual functions, classes, and modules work as expected before you use them to build larger stuff... From cjw at sympatico.ca Sat Mar 11 14:32:57 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 11 Mar 2006 14:32:57 -0500 Subject: Python source cross reference doc generator? In-Reply-To: References: Message-ID: Harry Fuecks wrote: > Hi All, > > Wondering if a tool exists to generate "cross reference" documentation > for Python code bases? > > Particularly after something like phpxref - > http://phpxref.sourceforge.net/ : written in Perl, scans a bunch of > PHP scripts and generates HTML output that allows you to see all the > classes / methods / functions / variables defined and (what I'm > interested in) where they are referenced. Essentially something like > API docs but with the addition of being able to see who's using a > particular method > > Is there anything like this for Python? Have done much looking without success. > > Many thanks. epydoc and pydoc each provides an index. If you are looking for info on where a name is defined or used, PyScripter is helpful. Colin W. From lycka at carmen.se Thu Mar 9 14:27:51 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 09 Mar 2006 20:27:51 +0100 Subject: String functions: what's the difference? In-Reply-To: <1hbxzk2.17m255b9li280N%h.c.de.jong@xxxxmsnet.nl.invalid> References: <978190B85Wile.E.Coyote@62.58.50.216> <1141916228.346552.64550@i39g2000cwa.googlegroups.com> <1hbxzk2.17m255b9li280N%h.c.de.jong@xxxxmsnet.nl.invalid> Message-ID: Harro de Jong wrote: > Thanks for the pointer. I was using time.time(), which I now see isn't > very accurate on Windows. time.clock() is more accurate on Windows (and much less so on Linux, where it also measures something completely different.) From python at cgcreator.com Sun Mar 12 08:50:32 2006 From: python at cgcreator.com (Keith) Date: Sun, 12 Mar 2006 21:50:32 +0800 Subject: Cross Module Command Useage Message-ID: <20060312135724.A09551E4007@bag.python.org> Ok so I'm new to the python programming language. and this is my first post to this mailing list. so here it is. So lets say have two modules.. moduleA and moduleB. they are both imported into a main python program using the "from module import *" command. now moduleA has a dynamic command that needs to access a command that is in moduleB. but when I run these modules from the main python scrip they cant see each other.. it gives me an error that the command does not exist. Dose this mean that I need to import moduleB into moduleA for it to see it. or is there a way that I can tell moduleA too look out to the main python program for the commands. I would hate to have to import lets say the "socket" module into every module rather than just having it look to the main module for the commands. -------------- next part -------------- An HTML attachment was scrubbed... URL: From samschul at pacbell.net Wed Mar 15 19:10:36 2006 From: samschul at pacbell.net (sam) Date: 15 Mar 2006 16:10:36 -0800 Subject: "pow" (power) function In-Reply-To: <1142465999.800332.73050@i39g2000cwa.googlegroups.com> References: <1142465999.800332.73050@i39g2000cwa.googlegroups.com> Message-ID: <1142467836.189959.116250@j33g2000cwa.googlegroups.com> I not shure which algorithm,but I am assumeing that all Python does,is to call the underlying C pow() function. Sam From brianwill1 at adelphia.net Mon Mar 13 02:15:33 2006 From: brianwill1 at adelphia.net (BWill) Date: Sun, 12 Mar 2006 23:15:33 -0800 Subject: Python IDE: great headache.... In-Reply-To: <4414099b@news.broadpark.no> References: <1142120002.912902.69630@i40g2000cwc.googlegroups.com> <4414099b@news.broadpark.no> Message-ID: Dag Fjeld Edvardsen wrote: > I like PyScripter. It has some of, but not all, the > features you request. > http://mmm-experts.com/Products.aspx?ProductId=4 > > -Dag > > Hey, that looks neat, and its open source too. Why have I not heard of it? I can have Eclipse-style sub-window management without the hassle of getting PyDev configured. What features exactly does it not have? From walterbyrd at iname.com Fri Mar 31 14:54:05 2006 From: walterbyrd at iname.com (walterbyrd) Date: 31 Mar 2006 11:54:05 -0800 Subject: Looking for a language/framework In-Reply-To: References: <1143559444.045808.38790@u72g2000cwu.googlegroups.com> Message-ID: <1143834845.208015.226710@e56g2000cwe.googlegroups.com> I am presently looking at a commercial product called dbqwiksite. I generates php code. I know that sounds lame, but the demos were impressive. If I could get the product to work like they show in the demos it would be great. It uses ODBC to connect to a mysql database; but I can't get it to work. From juho.schultz at helsinki.fi Thu Mar 9 05:00:21 2006 From: juho.schultz at helsinki.fi (Juho Schultz) Date: Thu, 09 Mar 2006 12:00:21 +0200 Subject: implementation of "complex" type In-Reply-To: <1141895757.128437.159460@i39g2000cwa.googlegroups.com> References: <1141895757.128437.159460@i39g2000cwa.googlegroups.com> Message-ID: Russ wrote: > I tried the following: > > >>>>x = complex(4) >>>>y = x >>>>y *= 2 >>>>print x, y > > (4+0j) (8+0j) > > But when I tried the same thing with my own class in place of > "complex" above, I found that both x and y were doubled. I'd like to > make my class behave like the "complex" class. Can someone tell me the > trick? Also, where can I find the code for for the "complex" class? I > hope it's written in Python! Thanks. > This is like the difference of tuples and lists. Your own class is mutable. y=x # Names x and y are now bound to the same object. y*=2 # change the object bound to names x and y. Builtin complex is immutable, so you can not manipulate the contents. y*=2 # creates a new object (value = 2*y), binds it to name y. From mscottschilling at hotmail.com Mon Mar 20 02:24:26 2006 From: mscottschilling at hotmail.com (Mike Schilling) Date: Mon, 20 Mar 2006 07:24:26 GMT Subject: Xah's Edu Corner: What is Expressiveness in a Computer Language References: <1142490052.127055.50130@v46g2000cwv.googlegroups.com> <1142802198.068034.157610@g10g2000cwb.googlegroups.com> Message-ID: "Xah Lee" wrote in message news:1142802198.068034.157610 at g10g2000cwb.googlegroups.com... >What is Expressiveness in a Computer Language >Xah Lee, 200502, 200603. >In languages human or computer, there's a notion of expressiveness. >English for example, is very expressive in manifestation, witness all >the poetry and implications and allusions and connotations and >dictions. Though at times, English fails to express anything whatsoever. From michele.simionato at gmail.com Fri Mar 24 03:25:32 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 24 Mar 2006 00:25:32 -0800 Subject: Strange metaclass behaviour In-Reply-To: <1143138624.25186@news.aic.at> References: <1143127358.820526.259930@i40g2000cwc.googlegroups.com> <1143138624.25186@news.aic.at> Message-ID: <1143188732.510491.233900@t31g2000cwb.googlegroups.com> > After 5 years of Python, I still find it impressive how much > vodoo and mojo one can do here :-) True ;) However, I should point out that I never use this stuff in production code. I have found out that for my typical usages metaclasses are too much: a class decorator would be enough and much less fragile. At the present, we do not have class decorators, but we can nearly fake them with a very neat trick: def thisclass(proc, *args, **kw): """ Example: >>> def register(cls): print 'registered' ... >>> class C: ... thisclass(register) ... registered """ # basic idea stolen from zope.interface, which credits P.J. Eby frame = sys._getframe(1) assert '__module__' in frame.f_locals # inside a class statement def makecls(name, bases, dic): try: cls = type(name, bases, dic) except TypeError, e: if "can't have only classic bases" in str(e): cls = type(name, bases + (object,), dic) else: # other strange errors, such as __slots__ conflicts, etc raise del cls.__metaclass__ proc(cls, *args, **kw) return cls frame.f_locals["__metaclass__"] = makecls Figured you would like this one ;) Michele Simionato From JordanGreenberg at gmail.com Mon Mar 20 16:11:52 2006 From: JordanGreenberg at gmail.com (Jordan Greenberg) Date: 20 Mar 2006 13:11:52 -0800 Subject: Function params with **? what do these mean? In-Reply-To: <1142887602.977736.300990@u72g2000cwu.googlegroups.com> References: <1142887602.977736.300990@u72g2000cwu.googlegroups.com> Message-ID: <1142889112.282294.83390@i40g2000cwc.googlegroups.com> in the parameter list, **param gets a dict of arguments that dont correspond to somthing in the formal parameter list. More & examples in the python docs: http://docs.python.org/tut/node6.html#SECTION006720000000000000000 -- Jordan T. Greenberg From hosalo at _NO_SPAM_gmail.com Sun Mar 19 10:11:11 2006 From: hosalo at _NO_SPAM_gmail.com (Heikki Salo) Date: Sun, 19 Mar 2006 15:11:11 GMT Subject: C-API: A beginner's problem In-Reply-To: References: Message-ID: Heikki Salo wrote: > Fabian Steiner wrote: >> What did I do wrong? As I am quite new to C, I probably made many >> mistakes, so please feel free to correct me. > > The following line: > > > for (i = 0; i <= seqlen; i++) { > > Should be "for (i = 0; i < seqlen; i++) {". Otherwise the last > assignment will be out of bounds and probably corrupts heap. And closer look tells that the code should not even compile. Is the code cut & pasted directly? Line "list[i] = item;" tries to assign a pointer to an int-array, which should not compile. There are other similar oddities. From No_4 at dsl.pipex.com Mon Mar 13 20:43:45 2006 From: No_4 at dsl.pipex.com (Big and Blue) Date: Tue, 14 Mar 2006 01:43:45 +0000 Subject: sizeof(struct timeval) In-Reply-To: References: Message-ID: Big and Blue wrote: > Tony Houghton wrote: >> >> How safe would I be assuming that >> sizeof(struct timeval) == 2 * sizeof(long) >> >> is always true on Linux on different architectures? > > Based on what I was looking at today (well, yesterday now), you might > be wrong. However, it looks as though I was wrong: linux/time.h: struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseconds */ }; time.h: typedef __time_t time_t; sys/time.h: typedef __suseconds_t suseconds_t; bits/types.h: __STD_TYPE __TIME_T_TYPE __time_t; /* Seconds since the Epoch. */ ... __STD_TYPE __SUSECONDS_T_TYPE __suseconds_t; /* Signed count of microseconds */ bits/typesizes.h: #define __TIME_T_TYPE __SLONGWORD_TYPE ... #define __SUSECONDS_T_TYPE __SLONGWORD_TYPE bits/types.h: #define __SLONGWORD_TYPE long int -- Just because I've written it doesn't mean that either you or I have to believe it. From michaeltaft at gmail.com Sat Mar 11 14:59:43 2006 From: michaeltaft at gmail.com (mwt) Date: 11 Mar 2006 11:59:43 -0800 Subject: Help Create Good Data Model Message-ID: <1142107183.358685.266440@i39g2000cwa.googlegroups.com> Hi. I'm reworking a little app I wrote, in order to separate the data from the UI. As a start, I wanted to create a iron-clad data recepticle that will hold all the important values, and stand up to being queried by various sources, perhaps concurrently. In all likelihood, the app will never need anything that robust, but I want to learn to write it anyway, as an exercise. So here is my code. It's really simple, and I'm sure you can see my Java background. Are there any problems here? Something I'm missing or screwing up? I welcome any and alll feedback, especially if it includes the *why's.* Thanks! #!/usr/bin/python # author mwt # Mar '06 import copy, threading class FAHData(object): """The data model for the F at H monitor.""" def __init__(self): self.data = {}#this dict will hold all data self.mutex = threading.RLock() def get_all_data(self): """Returns a COPY of entire data dict.""" #not sure deepcopy() is really necessary here #but using it for now #might cause some weird synchronization problems... try: self.mutex.acquire() return copy.deepcopy(self.data) finally: self.mutex.release() def get_data(self, key): """Returns a COPY of data element.""" try: self.mutex.acquire() return copy.deepcopy(self.data[key]) finally: self.mutex.release() def set_value(self, key, value): """Sets value of data element.""" try: self.mutex.acquire() self.data[key] = value finally: self.mutex.release() def set_data(self, data): """Sets entire data dictionary.""" try: self.mutex.acquire() self.data = data finally: self.mutex.release() def clear_data(self): """Clears entire data dictionary.""" try: self.mutex.acquire() self.data = {} finally: self.mutex.release() From onurb at xiludom.gro Thu Mar 23 17:18:50 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 23 Mar 2006 23:18:50 +0100 Subject: Per instance descriptors ? In-Reply-To: References: <44211ee8$0$7890$636a55ce@news.free.fr> <44226a82$0$20833$636a55ce@news.free.fr> <4422dd63$0$7687$636a55ce@news.free.fr> Message-ID: <44231e3b$0$24259$636a55ce@news.free.fr> Steven Bethard wrote: (snip code) > > But that looks pretty nasty to me. > It sounds like your architecture > could use some redesigning Done - in much more sane way. Got rid of some more boilerplate and of the whole problem of per-instance descriptors BTW !-) I should probably sleep more and program less... Thanks again, Steven. You've been of great help - even if indirectly. Remind me to buy you a beer if we ever meet !-) -- 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 Mar 31 05:03:27 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 31 Mar 2006 12:03:27 +0200 Subject: Best IDE for Python? In-Reply-To: References: <442ce5fa$0$6691$626a54ce@news.free.fr> Message-ID: <442cfeb2$0$13234$626a54ce@news.free.fr> Duncan Booth wrote: > Fredrik Lundh wrote: > > >>as you can see, Microsoft's usability team has made some massive >>improvements (note how well it deals with the "eat flaming death" >>command): > > > I especially like the way running it messes up the prompt: > > C:\Documents and Settings\Duncan>edlin > File name must be specified > > C:\DOCUME~1\Duncan> > > Yup, wanting to run something that archaic means you must also want to not > see those fancy filenames. Fancy filenames ? WHO needs fancy filenames ? FANCYF~1.EXT filenames should be enough for anybody !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From aleaxit at yahoo.com Mon Mar 27 21:38:38 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 27 Mar 2006 18:38:38 -0800 Subject: detecting drives for windows and linux References: <3uGdnTOPm5PGCrjZnZ2dnUVZ_u2dnZ2d@adelphia.com> <1143317936.422335.294230@u72g2000cwu.googlegroups.com> <1hcspu8.1c95yto1k8d87dN%aleaxit@yahoo.com> <20060327035701.2605.4.NOFFLE@dieschf.news.arcor.de> Message-ID: <1hcvfbg.1bxkk5y9v1bjpN%aleaxit@yahoo.com> Florian Diesch wrote: ... > >> are and want to do it anyway?) Linux puts the whole file system > >> (including mounted iPods, ISOs and NTFS drives) in one hierarchy. > > > > Yes, but you may still want to distinguish (because, for example, hard > > linking doesn't work across filesystems, and mv is not atomic then). > > Why not use os.stat? Each os.stat call gives you information about one file (or directory); it may be simpler and faster to get the information "in bulk" once and for all. > > Running a df command is a good simple way to find out what drives are > > mounted to what mountpoints -- the mount command is an alternative, but > > its output may be slightly harder to parse than df's. > > Executing df may be expensive if it needs to read some slow file systems. That's what the -n flag is for, if you're worried about that (although I believe it may not be available on all systems) -- executing mount is the alternative (just putting up with some parsing difficulties depending, e.g., on what automounters may be doing). > Reading /etc/mtab is not difficult and much faster $ cat /etc/mtab cat: /etc/mtab: No such file or directory Oops! BSD systems don't have /etc/mtab... so, if you choose to get your info by reading it, you've just needlessly destroyed your program's compatibility with a large portion of the Unix-y universe. popen a mount or df, and information will be easier to extract portably. Alex From daniel.dittmar at sap.corp Wed Mar 22 11:53:57 2006 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Wed, 22 Mar 2006 17:53:57 +0100 Subject: import random module In-Reply-To: <1143046086.771003.43180@g10g2000cwb.googlegroups.com> References: <1143046086.771003.43180@g10g2000cwb.googlegroups.com> Message-ID: DataSmash wrote: > Hi, > When I import the random module at the python interpreter, it works > fine: >>>> import random >>>> x = random.randint(1,55) >>>> print x > 14 > > BUT, when I put the same code in a python script: > * random.py: > > import random > > x = random.randint(1,55) > print x > > and run it at the command line, I get: > Traceback (most recent call last): > File p:\temp\random.py, line 7, in ? > import random > File p:\temp\random.py, line 8, in ? > x = random.randint(1,55) > AttributeError: 'module" object has no attribut 'randint' > > I run scripts at the command line everyday so there must be something > specifically > wrong with the "random" module, unless I'm totally missing something > here. Just put a print random after the import random.py You'll probably see that Python is importing your main module instead of the one from the lib. Daniel From no-spam at no-spam-no-spam.com Sat Mar 11 10:30:20 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 11 Mar 2006 16:30:20 +0100 Subject: "RuntimeError: dictionary changed size during iteration" ; Good atomic copy operations? In-Reply-To: <104lhpbuofu4l.jz32d3oa1uk7$.dlg@40tude.net> References: <104lhpbuofu4l.jz32d3oa1uk7$.dlg@40tude.net> Message-ID: EleSSaR^ wrote: > robert si ? profuso/a a scrivere su comp.lang.python tutte queste > elucubrazioni: > > [cut] > > I don't know what's your code like, but a similar error occurred in some of > my software and it was my fault indeed. I think you should either use a > lock, or implement a deepcopy method of your own. 100s of locks? no (see other message). It should be own deepcopy: thus, do you already know if the existing deepcopy has the same problem as cPickle.dump ? (as the problem araises rarely, it is difficult for me to test it out) Robert PS: how does ZODB work with this kind of problem? I thought is uses cPickle? From caleb.hattingh at gmail.com Thu Mar 16 15:57:18 2006 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 16 Mar 2006 12:57:18 -0800 Subject: Counting nested loop iterations In-Reply-To: <1142539976.631204.108260@u72g2000cwu.googlegroups.com> References: <1142539976.631204.108260@u72g2000cwu.googlegroups.com> Message-ID: <1142542638.360353.50340@p10g2000cwp.googlegroups.com> Hi Derek I went for an embarrassingly long time without knowing about "enumerate()". It doesn't directly answer your question about counting *within* nests, but I am going to tell you this on the off chance you don't know yet (and apologies if you do): This: count = 0 for animal in zoo: a = animal anum = count count = count + 1 IS a kludge, when you have this available to you: for count, animal in enumerate(zoo): a = animal anum = count I won't say how long it took me to start using list comprehensions :) regards Caleb From mailpitches at email.com Fri Mar 17 19:37:19 2006 From: mailpitches at email.com (mailpitches at email.com) Date: 17 Mar 2006 16:37:19 -0800 Subject: Python execution problem Message-ID: <1142642239.757552.44260@z34g2000cwc.googlegroups.com> Using OSX 10.4.5 This is more of a unix/tcsh question than a python question. Somehow I got to the point where I have two files 'a.py' and 'b.py' which have identical contents and permissions, but one refuses to execute: [blah:/Library/WebServer/CGI-Executables] me% a.py tcsh: a.py: Command not found. [blah:/Library/WebServer/CGI-Executables] me% b.py okay [blah:/Library/WebServer/CGI-Executables] me% Could someone enlighten me about how the shell knows to execute a script? I always assumed it was just the extension, but this seems to prove me wrong. tnx>mp From tim.golden at viacom-outdoor.co.uk Thu Mar 2 08:41:10 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 2 Mar 2006 13:41:10 -0000 Subject: why? [win32com/WMI] Message-ID: <9A28C052FF32734DACB0A288A3533991044D25DA@vogbs009.gb.vo.local> [Sergey] | Yes, I had run it. | | And, just now I updated python, pythonwin and wmi.py to | latest version. And got: | | >>> a=wmi.WMI() | >>> a.Win32_Process.Create(CommandLine="notepad.exe") # | --- it works | >>> a.Win32_Process.new().Create(CommandLine="notepad.exe") | # it still fail | Traceback (most recent call last): | File "", line 1, in ? | File "wmi.py", line 361, in __call__ | handle_com_error (error_info) | File "wmi.py", line 208, in handle_com_error | raise x_wmi, "\n".join (exception_string) | wmi.x_wmi: -0x7ffdfff7 - Exception occurred. | Error in: SWbemObjectEx | -0x7ffbefff - Generic failure | | Without 'new' everything works. And does everything I need from it. Yes, I think the simple answer is: don't use .new unless you're sure you need to. When I wrote the wmi module originally, I misunderstood the use of SpawnInstance_ (which is the method behind .new). To create a process, or a share, or anything which has a .Create method, use the .Create method. Use .new only for things like Win32_ProcessStartup, as in this example here: http://timgolden.me.uk/python/wmi_cookbook.html#run-process-minimised where the instance is created only to pass as a parameter into the .Create method of the Win32_Process. I've updated the module docstring for the next release, and have changed the cookbook examples which used .new where they shouldn't have, so thanks for highlighting the deficiency. | And, I have another question. Is there way to access WMI from linux? Not using this module, which is very Windows-specific; there was some work recently on WBEM (which is the industry standard behind WMI) on Linux, but I've not tried to use it myself: http://pywbem.sourceforge.net/ 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 mcfletch at rogers.com Sat Mar 11 15:56:14 2006 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 11 Mar 2006 15:56:14 -0500 Subject: Cheese Shop: some history for the new-comers In-Reply-To: References: <44126523$0$1016$afc38c87@news.optusnet.com.au> Message-ID: <4413396E.5040707@rogers.com> A.M. Kuchling wrote: > On Sat, 11 Mar 2006 16:50:26 +1100, > richard wrote: > >> So I did what people always do in this situation, I asked Barry Warsaw to >> name. it. And he did, "Cheese Shop". I liked the name, so it was done. When >> the new pydotorg machines went live last year, so too did the name >> cheeseshop.python.org >> > > Given the endless whiny complaints about the name, though, I think we > should just give up and go back to PyPI (pronounced 'Pippy'). > I realise it's an incredibly boring name, but what about pronouncing it as "the package index" or "the Python Package Index". Spelling it "PyPI" if one insists on a very short name in some written context is fine, but try not to use it when talking to a new user. That is, link to the page as "The Package Index" from www.python.org, refer to it as "you can find that in the package index", or "The Python Package Index has modules for X, Y, and Z" in a non-Python context. Use pippy if you're talking with someone deeply embedded in Python culture (maybe), but don't expect people to know what you're talking about. Use "the Cheese Shop" similarly. Luckily, www.python.org already does this, so no change is really required, it's only the server-name that says "cheeseshop", everything else says "Package Index" (that I could find)... Which boils down to "don't call it the cheese shop or pippy when you're talking to new users", maybe don't even call it that when you're talking to *anyone* who's not deeply pythonified, but feel free to think of it as the cheese shop or pippy. The familiar names, cute as they may be, don't really help users much. That is, make it an in-joke if you like, but assume that users will refer to it via the obvious, simple description of what it is and target documentation and communication appropriately. When/if the user "gets" that the Package Index is the Cheese Shop they can feel great having pierced that bubble, but don't force them to pierce it to get the software they need. Just my two cents, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From 3dbernard at gmail.com Tue Mar 21 15:47:51 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Tue, 21 Mar 2006 15:47:51 -0500 Subject: Problems writing to file Message-ID: <61d0e2b40603211247pf3bdb9cqf64469d4d77a7a5c@mail.gmail.com> Hello, I have this strange problem. I have written a program that writes a log to a log file. To start the program (I'm on Linux Fedora Core 3), I used a service. This service runs a bash file, wich in turn runs the Python top program file. Sooner or later the program stops writing to the log file. I have absolutely no clue why would that happen. Since the output of the Python program is not redirected other than to this log file, I have no idea why it's doing this. But the Python process appears still alive and well! But the strange thing is that if I run the program directly from a bash shell, no problem whatsoever, the programs runs smoothly and never stops writing to the file, until I kill it. Any suggestion? Thanks in advance Bernard From mtobis at gmail.com Wed Mar 8 12:02:19 2006 From: mtobis at gmail.com (Michael Tobis) Date: 8 Mar 2006 09:02:19 -0800 Subject: Python advocacy in scientific computation In-Reply-To: References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> <1141583453.403143.189400@i40g2000cwc.googlegroups.com> <1141750637.180979.69890@j33g2000cwa.googlegroups.com> Message-ID: <1141837339.598657.177260@j52g2000cwj.googlegroups.com> I think I agree with Steve here. I suspect you should either have sufficiently trained your users in Python, or have limited them to one-line statements which you could then strip of leading whitespace before passing them to Python, or even offered the alternative of one or the other. This would not have been much extra work. As for shell scripts generating Python code, I am not sure what you were trying to do, but if you're going that far why not just replace the shell script with a python script altogether? os.system() is your friend. I also agree with Steve that I can't see what this has to do with makefiles. (But then I think "make" is a thoroughly bad idea in the first place, and think os.system() is my friend.) mt From iainking at gmail.com Wed Mar 8 07:51:40 2006 From: iainking at gmail.com (Iain King) Date: 8 Mar 2006 04:51:40 -0800 Subject: wxPython GenericDirCtrl events In-Reply-To: References: <1141820738.244867.202420@i39g2000cwa.googlegroups.com> Message-ID: <1141822300.386612.37380@u72g2000cwu.googlegroups.com> Franz Steinhaeusler wrote: > On 8 Mar 2006 04:25:38 -0800, "Iain King" wrote: > > > >at the end TestPanel.__init__ I added: > > > >self.Bind(wx.EVT_TREE_SEL_CHANGED, self.test, dir1) > >{...] > > Try this instead: > > t = dir1.GetTreeCtrl() > t.Bind(wx.EVT_TREE_SEL_CHANGED, self.test) > > > -- > Franz Steinhaeusler Perfect. Thanks! Iain From finite.automaton at gmail.com Mon Mar 13 14:13:02 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 13 Mar 2006 11:13:02 -0800 Subject: Very, Very Green Python User In-Reply-To: <1142215118.291132.130490@e56g2000cwe.googlegroups.com> References: <1142215118.291132.130490@e56g2000cwe.googlegroups.com> Message-ID: <1142277182.747035.205280@i39g2000cwa.googlegroups.com> > Python closures are apparently very poor, but from what I can surmise > of the PyGTK2 page, instances of objects are dynamic enough to add new > methods, so you get your callbacks, at least. It's true that Python's "lambda" is somewhat limited, but this is rarely a problem because you can define named functions on-the-fly. > Double-underscore methods are rewritten with the class name? That's an ugly hack Yes, it is. But in practice, you will rarely need to pay attention to this. I'd been using Python for two years before I noticed this odd behavior. I heartily applaud shopping around for new languages. Coming from Perl, I think you'll find Python to be a figurative breath of fresh air, but you might also want to look at languages like Ruby, Haskell, etc. From scott.daniels at acm.org Fri Mar 17 17:55:58 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 17 Mar 2006 14:55:58 -0800 Subject: Python installation problem In-Reply-To: <1142635658.097143.261790@j52g2000cwj.googlegroups.com> References: <1142635658.097143.261790@j52g2000cwj.googlegroups.com> Message-ID: <441b3c3e@nntp0.pdx.net> mailpitches at email.com wrote: > I'm using OS X 10.4.5. I have an easy problem that I can't solve: > I have two versions of python installed. 2.3 came with the OS and 2.4 I > installed via fink.... > 2. How do I uninstall v. 2.3 completely. Probably not the greatest idea, because pieces of OS X may actually use the internal Python 2.3. --Scott David Daniels scott.daniels at acm.org From steve at holdenweb.com Tue Mar 21 13:00:47 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 21 Mar 2006 18:00:47 +0000 Subject: Module import information In-Reply-To: <76515c6c0603210904pedc11a8n2c49fac93e60c7c4@mail.gmail.com> References: <76515c6c0603210549k7576a94j87bde2da463e8f7f@mail.gmail.com> <76515c6c0603210904pedc11a8n2c49fac93e60c7c4@mail.gmail.com> Message-ID: Eric White wrote: > Peter: > > Thanks for the reply. Consider the following situation: > > A set of variable names is defined along with a list of possible values > for each. A second set of variable names is defined along with an > expression for generating a value for each. For each possible > permutation of variables from the first set, a python script is created > that contains commands that initialize the variable set with the > permuted values. A second python script is created that contains > commands for connecting to a database and storing the values of the > second set of variables after running the associated expression for each. > > We would like to be able to use the scripts above to drive a python > script containing a system of equations specified at run time and to > store the results. This "master" script contains the following calls: > > import somemodule > > # do stuff ... > > # initialize permuted variables > somemodule.init() > > # do more stuff ... > > # store results > somemodule.save() > > # do more stuff ... Etc. > > We would like for the call to init to initialize variables in the > context of the "master" script. To do this inside somemodule we use the > sys.modules dictionary to find a reference to the master module by name > and initialize variables at this reference. > > What I would like to know if it is arbitrarily possible to "walk" the > import hierarchy from any point. It is not apparent that python's > optimization of subsequent imports of the same module is relavent. > It seems to me that you could achieve the same end by accessing the calling stack frame inside the calls to your somemodule.functions(). Whether this is acceptable or not (and whether you are prepared to put up with the necessary voodoo) is another question. However, this would lead to atrocious coupling in your program. It's the kind of thing people used to use Fortran common blocks for, for goodness sake! The point Peter was trying to make about the distinction between first import of a module and subsequent ones is, I suspect, quite relevant, as you made it appear that you wanted to rely on code executed *during the import* to distinguish its importer. Clearly this would only be possible on the first import, as subsequent imports wouldn't execute the module's code. But now it appears that the import structure isn't really as relevant as the calling relationships anyway, no? Or am I misunderstanding your intent? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From aleaxit at yahoo.com Fri Mar 10 01:54:05 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Mar 2006 22:54:05 -0800 Subject: Why property works only for objects? References: Message-ID: <1hbyfgj.a3p39r1smomavN%aleaxit@yahoo.com> Michal Kwiatkowski wrote: ... > The problem is I have an instance of a given class (say BaseClass) and I > want it to implement some attribute accesses as method calls. I'm not a > creator of this object, so changing definition of BaseClass or > subclassing it is not an option. Wrong! Of _course_ it's an option -- why do you think it matters at all whether you're the creator of this object?! > Code below doesn't work, but shows my > intention: > > # obj is instance of BaseClass > def get_x(self): > # ... > def set_x(self, value): > # ... > obj.x = property(get_x, set_x) def insert_property(obj, name, getter, setter): class sub(obj.__class__): pass setattr(sub, name, property(getter, setter)) obj.__class__ = sub See? Of COURSE you can subclass -- not hard at all, really. Alex From steve at holdenweb.com Sat Mar 25 17:09:30 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 25 Mar 2006 22:09:30 +0000 Subject: pondering about the essence of types in python In-Reply-To: <1143318547.286867.9940@u72g2000cwu.googlegroups.com> References: <1143318547.286867.9940@u72g2000cwu.googlegroups.com> Message-ID: gangesmaster wrote: > let's start with a question: > > ========== > >>>>class z(object): > > ... def __init__(self): > ... self.blah=5 > ... > >>>>class x(object): > > ... def __init__(self): > ... z.__init__(self) > ... > >>>>y=x() > > Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in __init__ > TypeError: unbound method __init__() must be called with z instance as > first argument (got x instance instead) > ========== > > and the question is -- WHY? > > what is a type? generally speaking, if everything were an object, the > type only defines the MRO (method resolution order) for that object. > x.y first looks at the instance, then the class, then the parent > classes, etc. (this was changed a little in python2.3 to something more > complicated, but it's basically the same). > > you can see the mro like this: > ========== > >>>>class x(object): pass >>>>class y(x): pass >>>>class z(y): pass >>>>a=z() >>>>print a.__class__.mro() > > [, , , > ] > ========== > > after all, if we stay out of builtin types, all python objects are > dicts, which support chian-lookup according to the mro. and a method is > just a function that takes the instance as a first argument. so why is > all this type hassle necessary? > > if we've taken it that far already, then let's really go over the edge. > I WANT TO DERIVE FROM INSTANCES. not only types. > > why? i'm the developer of rpyc (http://rpyc.sf.net), and i got a > request from someone to add support for deriving from remote types. the > concrete example he gave was quite silly, but after i thought about it > a little, i said why not try? > > a little intro about rpyc: it gives you proxies (instances) to remote > objects, which can be instances, functions, or classes. and that user > wanted to do something like this: > > class my_frame(conn.modules.wx.Frame): > ... > > so the client was actually creates the graphics on the server. not very > usable, but why not? all it means is, when he does "my_frame.xyz", > python should add the remote type to the mro chain. not too bizar. > > but __mro__ is a readonly attribute, and deriving from instances is > impossible (conn.modules.wx.Frame is a PROXY to the class)... > > and again -- WHY? these all look like INTENTIONAL limitations. someone > went around and added type checks (which are NOT pythonic) into the > cPython implementation. argh. why do that? > > so i thought -- let's be nasty. i created a function that creates a > class that wraps an instance. very ugly. small children and peope with > heart problems should close their eyes. > > ============ > def derive_from(obj): > class cls(object): > def __getattr(self, name): > return getattr(obj, name) > return cls > > class my_frame(derive_from(conn.modules.wx.Frame)): > .... > ============ > > the actual implementation is quite more complex, but that shows the > concept. > so now i'm experimenting with that little shit. but then i came to the > problem that methods check the type of the first argument... ARGH. dont > check types. DONT. the whole point of duck-typing is you DONT CHECK THE > TYPES. you just work with objects, and instead of TypeError you'd get > AttribiuteError, which is much better. AAARRRRRRGGGHH. > > python is EVIL at the low level. the high-level is just fine, but when > you try to go under the hood... you better go with an exorcist. > Take a look at languages like Self. Self was actually the first prototype-based OO language. You could consider Javascript to be a prototype-based language as well. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From http Thu Mar 30 23:13:09 2006 From: http (Paul Rubin) Date: 30 Mar 2006 20:13:09 -0800 Subject: Another proposed proposal: operator.bool_and / bool_or Message-ID: <7xzmj71cbu.fsf@ruckus.brouhaha.com> The suggestion is to add boolean and/or functions to the operator module, useful with "reduce". For some reason I thought these were already present, but they're not (were they removed?). There are already and_ and or_, but these are bitwise functions, not boolean operations. bool_and and bool_or would differ from the "and" and "or" keywords, since they're functions and cannot short-circuit. Specification: operator.bool_and(x,y) = (bool(x) & bool(y)) operator.bool_or(x,y) = (bool(x) | bool(y)) Use case: from operator import bool_and, bool_or def any(seq): return reduce(bool_or, seq, False) def all(seq): return reduce(bool_and, seq, True) Of course you could use map(bool,seq), but now that we have bools it's reasonable to have these boolean operations. From no-spam at no-spam-no-spam.com Sat Mar 11 12:25:20 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 11 Mar 2006 18:25:20 +0100 Subject: How to best update remote compressed, encrypted archives incrementally? In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Sat, 11 Mar 2006 16:09:22 +0100, robert wrote: > > >>>Lastly, have you considered that your attempted solution is completely the >>>wrong way to solve the problem? If you explain _what_ you are wanting to >>>do, rather than _how_ you want to do it, perhaps there is a better way. >> >>So, there seems to be a big barrier for that task, when encryption is on >>the whole archive. A complex block navigation within a block cipher >>would be required, and obviously there is no such (handy) code already >>existing. Or is there a encryption/decryption method which you can can >>use like a file pipe _and_ which supports 'seek'? > > > [snip] > > Let's try again: rather than you telling us what technology you want to > use, tell us what your aim is. I suspect you are too close to the trees to > see the forest -- you are focusing on the fine detail. Let's hear the big > picture: what is the problem you are trying to solve? Because, frankly, as > far as I can see, the solution you are looking for doesn't exist. But > maybe I'm too far from the forest to see the individual trees. > > "I need encryption that supports seek" -- no, that's you telling us _how_ > you want to solve your problem. > > Perhaps you can tick some/all of the following requirements: > > - low bandwidth usage when updating the remote site > > - transmission needs to be secure > > - data on the remote site needs to be secure in case of theft or break-ins > > - remote site is under the control of untrusted parties; > or remote site is trusted > > - remote site is an old machine with limited processing power and very > small disk storage; > or remote site can be any machine we choose > > - local site needs to run Windows/Macintosh/Linux/BSD/all of the above > > - remote site runs on Windows/Macintosh/Linux/BSD/anything we like > > - we are updating text files/binary files > > - anything else you can tell us about the nature of your problem The main requirement is, that it has to be become a cohesive, reusable, portable (FTP/SFTP standard) functionality as mentioned in the OP. A Python module at best. For integration in a bigger Python app. not a one-time admin hack with a bunch of tools to be fiddled together on each user machine. So the 'how' is mostly =='what'. Its a Python question so far. The last 2 methods I mentioned already are maybe a way to a compromise, (if integrated one-stream encryption cannot be managed) The only issue remaining: A native Python module for pgp-(pwd only)-encryption or another kind of good (commonly supported) encryption. ZIP2-encryption itself seems to be too weak? (Still so in recent ZIP formats? what about the mode of 7zip etc?) But I found no python modules for either. http://www.amk.ca/python/code/gpg just calls into an external gpg installation. Can the functionality of "gpg -c" maybe fiddled together with PyCrypto easily ? (variable length key/pwd only - no public key stuff required) And what about ZIP password-only encryption itself? Are there maybe any usable improvents ? And: when there are many files encrypted with the same password (both PGP and ZIP), will this decrease the strength of encryption? Robert From kay.schluehr at gmx.net Sat Mar 11 16:34:43 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 11 Mar 2006 13:34:43 -0800 Subject: How to refer to the function object itself in the function per se? In-Reply-To: <1142108608.559879.45560@i39g2000cwa.googlegroups.com> References: <1142108608.559879.45560@i39g2000cwa.googlegroups.com> Message-ID: <1142112883.126132.301290@j52g2000cwj.googlegroups.com> Sullivan WxPyQtKinter wrote: > So how > could I refer to the function object per se, in the body of the > function itself? Just use the name. def f(): print f.__name__ >>> f() f From bismuti at gmail.com Thu Mar 16 18:14:29 2006 From: bismuti at gmail.com (Peter Bismuti) Date: Thu, 16 Mar 2006 15:14:29 -0800 Subject: TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple' Message-ID: <383f77da0603161514w5a0988fp683788536756891c@mail.gmail.com> Can anyone explain this error message? Traceback (most recent call last): File "/acct/pjb9508/RAT/Scripts/PyQt/RatDialog.py", line 30, in NewClipButton_clicked self.rat.planeClip(self.o,"SQUARE"+str(self.squareCounter),width,origin) File "/acct/pjb9508/RAT/Scripts/PyQt/rat.py", line 12, in planeClip plane1[1] = origin[1]-width TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple' -- Peter Bismuti -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Dialog.py Type: text/x-python Size: 5270 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: RatDialog.py Type: text/x-python Size: 1126 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: mygui.py Type: text/x-python Size: 222 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: rat.py Type: text/x-python Size: 7101 bytes Desc: not available URL: From kent at kentsjohnson.com Fri Mar 31 13:50:51 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 31 Mar 2006 13:50:51 -0500 Subject: logging producing redundant entries In-Reply-To: References: Message-ID: <442d74ca$1_3@newspeer2.tds.net> Jed Parsons wrote: > Thanks, Peter and alex23, > > The metalog test shows that the code is only being executed once at a time. > > And if I take those lines and put them in a shell script (fixing the > FileHandler - sorry about the bad copy there), they work as expected, > producing a single log entry. > > So I'm left with: > > - logging code that works properly in isolation in a shell script > - zope extension code that gets called only once (metalog test) > - logging code produces multiple entries when executed in extension > - logging code seems to produce more and more entries over time > > Am I somehow accumulating a growing list of loggers by having this code > at the top of a zope Extension? If I cause the extension to be > re-evaluated, do I somehow attach another logger? (I'm grasping at > straws...) It sounds like Zope is reloading your extension. Each time it is reloaded you will attach another logger. > > I've tried the following to only call getLogger once, but it doesn't > seem to help: > > try: > _logger > except NameError: > _logger = logging.getLogger('login') > etc... No, that won't work if it really is a reload, _logger will never be defined. Can you put the logging setup somewhere else, in a module that is only loaded once? Or inspect _logger.handlers to see if it already contains a FileHandler to your log file, and only add it if it is not there already. Kent From seywaresolutions at gmail.com Tue Mar 28 15:30:46 2006 From: seywaresolutions at gmail.com (Chris S) Date: 28 Mar 2006 12:30:46 -0800 Subject: Quick Question regarding Frames In-Reply-To: <1143571941.731740.228960@g10g2000cwb.googlegroups.com> References: <1143555706.435922.309210@g10g2000cwb.googlegroups.com> <1143571941.731740.228960@g10g2000cwb.googlegroups.com> Message-ID: <1143577846.750248.107300@j33g2000cwa.googlegroups.com> HI Dave, Thanks for the reply. I am a bit confused by this piece of code: class FrameB(wx.Frame): def __init__(self, frameA, ...): self.frameA = frameA What is frameA in the __init__ definition? Do I need to create something called frameA in order to pass it to that __init__ function? Presently I would call FrameB as w2 = FrameB(None, -1,"") w2.Show() Where would I put the reference to frameA? Thanks. Chris From neurogasm at gmail.com Wed Mar 22 15:58:00 2006 From: neurogasm at gmail.com (Kevin F) Date: Wed, 22 Mar 2006 15:58:00 -0500 Subject: parsing downloaded mail via POP3 Message-ID: I have the following script: emails = [] for msg in messagesInfo: msgNum = int(msg.split()[0]) msgSize = int(msg.split()[1]) if(msgSize < 20000): message = server.retr(msgNum)[1] Message = join(message, ?\n?) emails.append(message) It downloads messages for me via my POP3 server, however, the message format (attached below) includes ridiculous amounts of data and I just want to return the from, subject, and body. Any pointers on how to do this? /// sample message downloaded fe5.bluebottle.com (fe5 [209.144.225.81])', '\t by bluebottle-be1.bluebottle.com (Cyrus v2.2.8) with LMTPA;', '\t Tue, 21 Mar 2006 23:47:22 -0600', 'X-Sieve: CMU Sieve 2.2', 'Received: from fe7.bluebottle.com (fe7 [209.144.225.70])', '\tby fe5.bluebottle.com (8.13.4/8.13.4) with ESMTP id k2M5hhkd023264', '\tfor ; Tue, 21 Mar 2006 23:44:35 -0600', 'Received: from smtp-relay.wharton.upenn.edu (smtp-relay.wharton.upenn.edu [130.91.161.218])', '\tby fe7.bluebottle.com (8.13.4/8.13.4) with ESMTP id k2M5hea4022775', '\t(version=TLSv1/SSLv3 cipher=DHE-RSA-AES256-SHA bits=256 verify=NO)', '\tfor ; Tue, 21 Mar 2006 23:43:41 -0600', 'Received: from FAIRMOUNT.wharton.upenn.edu (fairmount2.wharton.Upenn.Edu [128.91.87.58])', '\tby smtp-relay.wharton.upenn.edu (8.13.1/8.13.1) with ESMTP id k2M5heQv007094', '\tfor ; Wed, 22 Mar 2006 00:43:40 -0500', 'X-DomainKeys: Sendmail DomainKeys Filter v0.3.2 smtp-relay.wharton.upenn.edu k2M5heQv007094', 'DomainKey-Signature: a=rsa-sha1; s=smtp-relay; d=wharton.upenn.edu; c=nofws; q=dns;', '\tb=TZ7xn8PLJNMsq8iCl7eqlME0EDnCC7fKUvpKmALqe1FQ5gG/fG+V/bomQMKyblplJ', '\tlg6wTqPoeao6lkM4yu+Rw==', 'Received: from webmail1.wharton.upenn.edu ([172.16.32.58]) by FAIRMOUNT.wharton.upenn.edu with Microsoft SMTPSVC(6.0.3790.1830);', '\t Wed, 22 Mar 2006 00:43:39 -0500', 'Received: from [165.123.150.168] ([165.123.150.168]) by webmail1.wharton.upenn.edu over TLS secured channel with Microsoft SMTPSVC(6.0.3790.1830);', '\t Wed, 22 Mar 2006 00:43:39 -0500', 'User-Agent: Microsoft-Entourage/11.0.0.040405', 'Date: Wed, 22 Mar 2006 00:43:37 -0500', 'Subject: KNOCKITY-----KNOCK-----WHOS-----THERE', 'From: Kevin Feng ', 'To: "opim399fengk at bluebottle.com" ', 'Message-ID: ', 'Mime-version: 1.0', 'Content-type: text/plain;', '\tcharset="US-ASCII"', 'Content-transfer-encoding: 7bit', 'X-OriginalArrivalTime: 22 Mar 2006 05:43:39.0441 (UTC) FILETIME=[921A4210:01C64D73]', 'X-Virus-Scanned: ClamAV version 0.88, clamav-milter version 0.87 on fe7.bluebottle.com', 'X-Virus-Status: Clean', 'Trusted-Delivery-Validation-State: Not validated', '', 'ANITA-----ANITA WHO----ANITA BETTER JOKE', '', ''], 2266) From greg at cosc.canterbury.ac.nz Wed Mar 8 22:26:52 2006 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 09 Mar 2006 16:26:52 +1300 Subject: Python advocacy in scientific computation In-Reply-To: References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> <1141583453.403143.189400@i40g2000cwc.googlegroups.com> <1141750637.180979.69890@j33g2000cwa.googlegroups.com> <1141837339.598657.177260@j52g2000cwj.googlegroups.com> Message-ID: <479ljvFejot7U1@individual.net> Andy Salnikov wrote: > Actually os.system() is rather poor replacement for the shell's > capabilities, and it's _very_ low level, it's really a C-level code > wrapped in Python syntax. Since os.system() spawns a shell to execute the command, it's theoretically capable of anything that the shell can do. It's somewhat inelegant having to concatenate all the arguments into a string, though. I gather there's a new subprocess management module coming that's designed to clean up the mess surrounding all the popen() variants. Hopefully it will make this sort of thing a lot easier. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From johnjsal at NOSPAMgmail.com Thu Mar 2 13:20:13 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 02 Mar 2006 18:20:13 GMT Subject: import, from and reload In-Reply-To: References: Message-ID: Dave Benjamin wrote: > In general, "from X import *" should be avoided anyway, for reasons that > have been discussed many times in the past. The annoyance with reloading > is just one more reason. Better to just use "import X" in the first place. > Thanks. I kind of figured it's better to use import instead of from anyway, but I was following along with some examples that use from (despite the fact that earlier in the book they even say that from is problematic and you should use import instead!) :) From deets at nospam.web.de Mon Mar 27 09:04:07 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 27 Mar 2006 16:04:07 +0200 Subject: Difference between 'is' and '==' References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <1143462121.828462.34290@v46g2000cwv.googlegroups.com> <1143466119.249145.36960@i39g2000cwa.googlegroups.com> Message-ID: <48q9pfFlc8q0U1@uni-berlin.de> mwql wrote: > It's really strange, > > if > a = 1 > b = 1 > a is b ==> True > > the same thing applies for strings, but not for dict, lists or tuples > I think the 'is' operator is useful for objects only, not for primitive > types, > I think I solved the mystery behind my bugged code =) The reason that "is" works for small numbers is that these are cached for performance reasons. Try >>> a = 1000000 >>> b = 1000000 >>> a is b False So - your conclusion is basically right: use is on (complex) objects, not on numbers and strings and other built-ins. The exception from the rule is None - that should only exist once, so foo is not None is considered better style than foo == None. Diez From ramen at lackingtalent.com Tue Mar 28 18:14:32 2006 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 28 Mar 2006 17:14:32 -0600 Subject: Parsing csh scripts with python In-Reply-To: References: Message-ID: On Tue, 28 Mar 2006, David Hirschfield wrote: > I need to be able to parse the script, modify some variable settings and > then write the script back out so that the only changes are the > variables I've modified (comments, ordering of statements, etc. must > remain the same). > > I looked at shlex, but I don't think it will do what I need. What about regular expressions? -- .:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:. "one man's constant is another man's variable" - alan perlis From robert.kern at gmail.com Fri Mar 17 16:22:03 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 17 Mar 2006 15:22:03 -0600 Subject: My Generator Paradox! In-Reply-To: <1142624660.080497.51720@v46g2000cwv.googlegroups.com> References: <1142554666.740989.303350@p10g2000cwp.googlegroups.com> <1142624660.080497.51720@v46g2000cwv.googlegroups.com> Message-ID: vbgunz wrote: > I believe I understand now. the yield keyword is sort of like a cousin > to return. return will bring back an object I can work with and so does > yield *but* yield's object will most likely support the .next() method. No, that's not really how it works. When a generator function is called, it returns the generator object immediately. None of the code inside is executed. Every time you call that generator function, you get a new generator object with the initial state. The objects that are yielded inside the code don't show up yet. The code inside the generator gets executed only when the generator object is iterated over (or its .next() method is called). The objects that are yielded are the results of calling the .next() method. -- Robert Kern robert.kern at gmail.com "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 kent at kentsjohnson.com Mon Mar 20 11:42:11 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 20 Mar 2006 11:42:11 -0500 Subject: ** Operator In-Reply-To: References: <1142833145.976550.104830@v46g2000cwv.googlegroups.com> <1142833540.860154.137040@u72g2000cwu.googlegroups.com> <1hcgw5p.1ufznwe1lxeagfN%aleaxit@yahoo.com> <1142864492.645457.291240@j33g2000cwa.googlegroups.com> Message-ID: <441ed65c$1_3@newspeer2.tds.net> Christoph Zwerschke wrote: >>http://docs.python.org/lib/typesnumeric.html > > You're right, it's mentioned there in section 2.3.4, but the explanation > of pow() is already in section 2.1 prior to that. > > So it would be nice if the paragraph explaining pow() would mention that > you can also write x**y for pow(x,y). And/or the example given in the > paragraph should say pow(10,2) instead of 10**2. Otherwise it's a bit > confusing for somebody who reads in chronological order and doesn't know > about the ** syntax (many other languages write x^y instead of x**y). The way to make this change happen is to submit a bug report with your suggested change. See the link at the bottom of the above page to find out how. Kent From sybrenUSE at YOURthirdtower.com.imagination Tue Mar 14 05:04:09 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 14 Mar 2006 11:04:09 +0100 Subject: SSL/TLS - am I doing it right? References: <1142240607.501914.4390@j52g2000cwj.googlegroups.com> <1142247180.180132.256110@v46g2000cwv.googlegroups.com> <1142252828.097230.36540@e56g2000cwe.googlegroups.com> <1142328759.640029.202910@j52g2000cwj.googlegroups.com> <7xy7zdnywx.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin enlightened us with: > If you're paranoid, you can scrounge some $20 obsolete laptop from > ebay and dedicate it to use as a CA, never letting it touch the > internet (transfer files to and from it on floppy disc). caCert use a special box for this too. It has no network connection, and communicates through a serial cable. All it does with that serial cable is accept certificate requests and spit out signed certificates :) 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 mtobis at gmail.com Sat Mar 11 15:01:01 2006 From: mtobis at gmail.com (Michael Tobis) Date: 11 Mar 2006 12:01:01 -0800 Subject: New python.org site In-Reply-To: References: <1142094677.527237.322080@e56g2000cwe.googlegroups.com> Message-ID: <1142107260.898369.272940@u72g2000cwu.googlegroups.com> I think a logo contest is a good idea, and I am already working on my entry. I could also imagine a stylesheet contest. The issue is who does the judging and what are the criteria. Steve, what you say is true. Possibly people who are experienced in making a six page site for their aunt's catering business may not understand how much the site implementation is constrained by the huge amount of existing content, nor what an excellent effort the rework is, nor what a good product was achieved. I am trying to make the point that the silly logo cancels out a good bit of the benefit of the site in appealing to the uncommitted. A brand that people love is usually a part of a product that people love, and there needs to be some correspondence. A pink bunny is a fine brand for flashlight batteries, but not a good one for motorcycles. For a language which cannot avoid associations with a ten meter snake, a pair of tadpoles just says "we don't really mean it, never mind". The twistedmatrix logo and the pycon logo take advantage of the associations. The tadpoles try to avoid them, and to make matters worse pick up a vague and oddly disturbing religious affiliation in the process. If we are serious about promoting the language, they really have got to go. The contest can specify the dimensions of the logo image to match those of the one currently on the site. The amount of work required to replace the existing logo with a more appropriate one would amount to just changing one reference in a stylesheet. Michael From uymqlp502 at sneakemail.com Wed Mar 15 20:58:45 2006 From: uymqlp502 at sneakemail.com (Russ) Date: 15 Mar 2006 17:58:45 -0800 Subject: "pow" (power) function In-Reply-To: <1142470299.753531.269360@j52g2000cwj.googlegroups.com> References: <1142465999.800332.73050@i39g2000cwa.googlegroups.com> <1142470299.753531.269360@j52g2000cwj.googlegroups.com> Message-ID: <1142474325.396362.78920@u72g2000cwu.googlegroups.com> Ben Cartwright wrote: > Russ wrote: > > Does "pow(x,2)" simply square x, or does it first compute logarithms > > (as would be necessary if the exponent were not an integer)? > > > The former, using binary exponentiation (quite fast), assuming x is an > int or long. > > If x is a float, Python coerces the 2 to 2.0, and CPython's float_pow() > function is called. This function calls libm's pow(), which in turn > uses logarithms. I just did a little time test (which I should have done *before* my original post!), and 2.0**2 seems to be about twice as fast as pow(2.0,2). That seems consistent with your claim above. I'm a bit surprised that pow() would use logarithms even if the exponent is an integer. I suppose that just checking for an integer exponent could blow away the gain that would be achieved by avoiding logarithms. On the other hand, I would think that using logarithms could introduce a tiny error (e.g., pow(2.0,2) = 3.9999999996 <- made up result) that wouldn't occur with multiplication. > > > Does "x**0.5" use the same algorithm as "sqrt(x)", or does it use some > > other (perhaps less efficient) algorithm based on logarithms? > > The latter, and that algorithm is libm's pow(). Except for a few > special cases that Python handles, all floating point exponentation is > left to libm. Checking to see if the exponent is 0.5 is not one of > those special cases. I just did another little time test comparing 2.0**0.5 with sqrt(2.0). Surprisingly, 2.0**0.5 seems to take around a third less time. None of these differences are really significant unless one is doing super-heavy-duty number crunching, of course, but I was just curious. Thanks for the information. From cretin at des.alpes.ch Fri Mar 24 13:58:09 2006 From: cretin at des.alpes.ch (Azolex) Date: Fri, 24 Mar 2006 19:58:09 +0100 Subject: What's The Best Editor for python In-Reply-To: References: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> Message-ID: <4424414b_3@news.bluewin.ch> Wildemar Wildenburger wrote: > just to bloat this thread some more: > > Am I the only one using jEdit? I've yet to find better for developing in jython From m.wanstall at gmail.com Mon Mar 27 23:21:32 2006 From: m.wanstall at gmail.com (m.wanstall at gmail.com) Date: 27 Mar 2006 20:21:32 -0800 Subject: Plone or TurboGears for Intranet Message-ID: <1143519692.813820.290530@u72g2000cwu.googlegroups.com> Hi all, Just wondering which technology would best suit the development of custom intranets in general, things that may be industry specific would need to be included (say for an industrial design company the addition of internal memos and even extrememly business specific apps such as simple inventory control reporting). The other big issue is ease of templating as the only Plone examples I've seen have seemed to basically use the original template or a slightly customised version of it so I'm wondering whether it would be quicker to build it from the ground up with TurboGears. Any thoughts on the matter are greatly appreciated and any examples of EITHER used extensively in case studies or the like would be fantastic! Thanks in advance! From just at xs4all.nl Thu Mar 9 09:32:31 2006 From: just at xs4all.nl (Just) Date: Thu, 09 Mar 2006 15:32:31 +0100 Subject: First script, please comment and advise References: Message-ID: In article , Pedro Graca wrote: > I'm sure this isn't very pythonic; comments and advice appreciated > > > def curious(text): > """ Return the words in input text scrambled except for the first and > last letter. """ > new_text = "" > word = "" > for ch in text: > if ch in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ": > word = word + ch > else: > new_text = new_text + scramble(word) > word = "" > new_text = new_text + ch > return new_text > > def scramble(word): > """ scramble word """ > from random import randint > > if len(word) < 4: > return word > new_word = word[0] > > ### transform "curious" into ['u', 'r', 'i', 'o', 'u'] > letters = [] > for ch in word: > letters.append(ch) > del letters[0:1] > del letters[-1] > > ### why doesn't range(len(letters) - 1, 0, -1) work? > for i in range(len(letters) - 1, -1, -1): > j = randint(0, i) > new_word = new_word + letters[j] > del letters[j] > return new_word + word[-1] > > print curious(curious.__doc__) def curious(text): """ Return the words in input text scrambled except for the first and last letter. """ new_text = "" word = "" for ch in text: if ch.isalpha(): word += ch else: new_text += scramble(word) word = "" new_text += ch new_text += scramble(word) return new_text def scramble(word): """ scramble word """ from random import shuffle if len(word) < 4: return word letters = list(word[1:-1]) shuffle(letters) return word[0] + "".join(letters) + word[-1] Just From fredrik at pythonware.com Thu Mar 9 00:09:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 9 Mar 2006 06:09:37 +0100 Subject: Gathering screen output References: <57aa55060603081855x277d2672y827678447e1c63b4@mail.gmail.com> Message-ID: Greg Lindstrom wrote: > I'm running Python 2.4 on windows xp "professional" and seem to recall there > is a way to kick off system command (or any external routine) and then > collect the screen output back into the calling python routine for > analysis. I've look and googled but have come up lacking. Please tell me > this is not a flashback to my days coding with another "P" language... the Python Imaging Library http://www.pythonware.com/products/pil has an ImageGrab module that can do exactly this: http://www.pythonware.com/library/pil/handbook/imagegrab.htm From aleaxit at yahoo.com Fri Mar 3 22:18:01 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 3 Mar 2006 19:18:01 -0800 Subject: do design patterns still apply with Python? References: <8SINf.1718$No6.40137@news.tufts.edu> <1141359639.306953.117990@v46g2000cwv.googlegroups.com> Message-ID: <1hbn1eq.17ey53q1pxxau3N%aleaxit@yahoo.com> gene tani wrote: ... > There's a couple Alex M slideshows and a couple discussions of > Creational/Structural / Behavioral patterns > > http://www.strakt.com/docs/ep04_pydp.pdf And more of my stuff (including slideshows on Design Patterns in Python, and one essay "Five easy pieces" on the Borg DP) can be found by starting at my homepage, http://www.aleax.it -- I've long dreamed of writing a book about Design Patterns and methodology in/for/with Python, but, it's unlikely to happen any time soon. > i think mostly i flip thru the Oreilly cookbook whenever i need > something. Yes, we have substantial numbers of DPs there, too, both 1st and 2nd editions (more, I believe in the 2nd ed). Alex From fredrik at pythonware.com Tue Mar 14 05:49:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Mar 2006 11:49:38 +0100 Subject: Is this possible in Python? References: <1142238871.199749.243470@p10g2000cwp.googlegroups.com><1142282467.270698.142780@p10g2000cwp.googlegroups.com> <1142331474.355167.20970@i40g2000cwc.googlegroups.com> Message-ID: "jalanb" wrote: > You might like the version here: > http://www.jorendorff.com/toys/out.html which only works if 1) you're using a Python implementation that supports those attributes, 2) the source code is available, 3) the expression is written on a single line, and 4) you don't use confusing comments after the function call (and probably some more things I cannot think of right now). perfectly valid Python constructs like out( temp ) or out(temp) # XXX: should use gettemp() instead breaks the function. > Especially the "need to know" presentation, which is cute indeed. From larry.bates at websafe.com Fri Mar 3 11:00:25 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 03 Mar 2006 10:00:25 -0600 Subject: How to find cause for Python/Pythonwin crash only on Dual Core Machines ? In-Reply-To: References: Message-ID: <44086819.2040401@websafe.com> robert wrote: > There is a strange freeze/crash only on dual core machines: > > I have a python app (Python 2.3.5 /Pythonwin build 203 / Windows) > running with no stability problems on normal machines (Or a crash is so > rare, that absolutely nobody obverses it, though the overall majority of > users uses single core machines). Threads, network & pythonwin/win32ui > all in use. > > Yet, from 3 users, _all_ using a Dual Processor System (XEON, amd x2 > 3800+) computer, I have reports, that the application freezes hard > and/or crashes with a kind of random stack dump (operating system). I > cannot experiment with those machines. > > I found no hints other than: > > http://groups.google.de/group/comp.lang.python/browse_frm/thread/64ca033e1a7f6c61/719b147e870bd5e6 > > > http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=480325 > > > .. both discussions remaining in uncertainty. > > Are there (known) problems with Python/Pythonwin specific for dual > core's (py2.3.5 / pywin203) ? > > What could I do to find the problem? > > Robert > > > -------------- > > PS: there is very little C extension-code (SWIG) involved, yet I looked > over that so often, I guess its save: > > > // > > #include "stdafx.h" > #include "commctrl.h" > #include "ext.h" > > BOOL APIENTRY DllMain( HANDLE hModule, > DWORD ul_reason_for_call, > LPVOID lpReserved > ) > { > return TRUE; > } > > class CAllowThreads { > public: > PyThreadState *_save; \ > CAllowThreads() { > _save = PyEval_SaveThread(); > } > ~CAllowThreads() { > PyEval_RestoreThread(_save); > } > }; > > PyObject* PyListView_GetSubItemRect( > HWND hwndLV, > int iItem, > int iSubItem, > int code > // LPRECT lpRect > ) > { > RECT r; > { > CAllowThreads _t; > ListView_GetSubItemRect( > hwndLV, > iItem, > iSubItem, > code, > &r ); > } > return Py_BuildValue("iiii", r.left,r.top,r.right,r.bottom); > > } > > int GetStringAddr(const char* s) { > return (int)s; > } > > int PlaySoundResource(int resid, HMODULE hmod) > { > CAllowThreads _t; > return PlaySound(MAKEINTRESOURCE(resid), hmod, SND_RESOURCE); > } > > int PlaySoundFile(const char* fname, int flag) > { > CAllowThreads _t; > return PlaySound(fname, NULL, flag); > } > > PyObject* py_ToolTipRelayMsg( PyObject* self, PyObject* args ) > { > MSG msg; > HWND hwTT; > if(!PyArg_ParseTuple(args,"i(iiiii(ii)):ToolTipRelayMsg", > &hwTT, > > &msg.hwnd,&msg.message,&msg.wParam,&msg.lParam,&msg.time, > &msg.pt, ((int*)&msg.pt)+1) ) > return NULL; > > > { > CAllowThreads _t; > SendMessage(hwTT,TTM_RELAYEVENT,0,(LPARAM)&msg); > } > > Py_INCREF( Py_None ); > return Py_None; > } > > --- > > "GetStringAddress" is used only once like this (leades to correct NUL > termination I think): > > self.sb.SendMessage(commctrl.SB_SETTEXT,iPane,extension.GetStringAddr(text)) > > > --- swig: > static PyObject *_wrap_GetStringAddr(PyObject *self, PyObject *args) { > PyObject *resultobj; > char *arg0 ; > int result ; > > if(!PyArg_ParseTuple(args,(char *)"s:GetStringAddr",&arg0)) return > NULL; > result = (int )GetStringAddr((char const *)arg0); > resultobj = PyInt_FromLong((long)result); > return resultobj; > } I've run on Dual 1.7, 2.4Ghz Xeon machines and a hyperthreaded 3.0Ghz machine for several years with no problems. I don't think there is an inherent problem. -Larry Bates From fengk at wharton.upenn.edu Tue Mar 14 02:34:41 2006 From: fengk at wharton.upenn.edu (Kevin Feng) Date: Tue, 14 Mar 2006 02:34:41 -0500 Subject: Basic python help References: <2955b$44166cc5$506c2949$25559@news.chello.at> Message-ID: No idea, I do not have permission to access the error log. On 3/14/06 2:12 AM, in article 2955b$44166cc5$506c2949$25559 at news.chello.at, "Gregor Horvath" wrote: > Kevin Feng schrieb: > >> More information about this error may be available in the server error log. >> >> >> >> Any suggestions? Much thanks. >> > > What does the error log of the webserver say? > > -- > Greg From fredrik at pythonware.com Wed Mar 15 08:55:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Mar 2006 14:55:55 +0100 Subject: Install Universal Encoding Detector References: <1142430310.530681.321760@i39g2000cwa.googlegroups.com> Message-ID: "Jacob" wrote: > How do I install Universal Encoding Detector > (http://chardet.feedparser.org/)? it comes with a setup.py file, so I suppose the answer is "in the usual way": 1. download 2. unpack 3. cd to the distribution directory 4. run "python setup.py install" more here: http://docs.python.org/inst/inst.html From lycka at carmen.se Mon Mar 20 06:03:08 2006 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 20 Mar 2006 12:03:08 +0100 Subject: Importing an output from another function In-Reply-To: <1142629118.886810.251200@u72g2000cwu.googlegroups.com> References: <1142626528.204581.179350@v46g2000cwv.googlegroups.com> <1142627019.614450.250540@i40g2000cwc.googlegroups.com> <1142628076.041352.320560@i40g2000cwc.googlegroups.com> <1142629118.886810.251200@u72g2000cwu.googlegroups.com> Message-ID: Byte wrote: > Now what do I do if Func1() has multiple outputs and Func2() requires > them all to give its own output, as follows: > > import random > > def Func1(): > choice = ('A', 'B', 'C') > output = random.choice(choice) > output2 = random.choice(choice) > return output > return output2 > > def Func2(item1, item2): > print item1, item2 > > output1 = Func1() > Func2(output1) Some more options (untested): def func1(n, choice=('A', 'B', 'C')): # n=number of choices # choice can now be overridden with # other values choices = [] for i in range(n): choices.append(random.choice(choice)) return choices def func2(choices): for choice in choices: print choice, print func2(func1(2)) ######################################### class ChoosePrinter(object): def __init__(self, to_choose_from=('A', 'B', 'C')): self.to_choose_from=to_choose_from self.choosen = [] def get_choices(self, n=2): for i in range(n): self.choosen.append(random.choice(choice)) def dump_choosen(self): print " ".join(self.choosen) self.choosen = [] cp = ChoosePrinter() cp.get_choices(2) cp.dump_choosen() From hancock at anansispaceworks.com Wed Mar 8 20:19:42 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 8 Mar 2006 19:19:42 -0600 Subject: why no block comments in Python? In-Reply-To: <1141843360.140692.44180@i39g2000cwa.googlegroups.com> References: <_MCPf.1749$No6.40293@news.tufts.edu> <1141843360.140692.44180@i39g2000cwa.googlegroups.com> Message-ID: <200603081919.42490.hancock@anansispaceworks.com> On Wednesday 08 March 2006 12:42 pm, Warby wrote: > The danger with block comments is that there is no way to tell that the > code you're looking at has been commented out unless you can see the > start or end of the comment block. If you have a modern editor, it > probably changes the color of all commented out code to eliminate > confusion. But if you have a primitive editor it does not. Also, even > people who use modern editors sometimes browse source code using a > plain text viewer (less/more). No doubt some Emacs zealot will say something snarky at this point, ;-) but it's also true that Vi (or gvim anyway) will occasionally get confused by very long block comments or triple-quoted strings, causing the syntax-color to get out of synch. I recently started running into this problem when I started using doctest tests. There's probably a smarter way to do this, but I was putting several of them in a module docstring, and it gets to be a 100+ lines or so of doctest plus explanations. I'm thinking this might be a use-case for the new support for doctests in a separate file. Or maybe I just need to see if I can move the tests into individual object docstrings. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From ptmcg at austin.rr._bogus_.com Sat Mar 25 14:56:17 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 25 Mar 2006 19:56:17 GMT Subject: Custom behavior defined in the imported module References: <36fVf.16938$1Z5.10700@tornado.texas.rr.com> <44259839$1_2@newspeer2.tds.net> Message-ID: "Kent Johnson" wrote in message news:44259839$1_2 at newspeer2.tds.net... > Paul McGuire wrote: > > The alternatives I've come up with for the user to enable this packrat parse > > mode are: > > > > 1. Add a staticmethod enablePackrat() to the pyparsing ParserElement class, > > to modify the ParserElement defintion of the internal (non-packrat) parse() > > method. This method essentially runs code looking like: > > > > ParserElement.parse,ParserElement.originalParse = \ > > ParserElement.packratParse,ParserElement.parse > > Could you just define a module pyparsingpackrat like this: > from pyparsing import * > ParserElement.parse,ParserElement.originalParse = \ > ParserElement.packratParse,ParserElement.parse > > Then users would just import pyparsingpackrat instead of pyparsing. > > Kent (damned touchy touchpad!) ... anyway... I *really* like keeping pyparsing's footprint down to just one Python module. It would be nice if I could pass an argument along with the import statement: import pyparsing(packrat=True) or some such. -- Paul From JKPeck at gmail.com Mon Mar 6 18:01:33 2006 From: JKPeck at gmail.com (JKPeck) Date: 6 Mar 2006 15:01:33 -0800 Subject: Python and Java Message-ID: <1141686093.946407.245540@z34g2000cwc.googlegroups.com> Suppose you have an application written in Java, and you want to enable other applications or processes written in Python to communicate with it, i.e., to use Python as a scripting language for the application. On Windows you could do this with COM and various addons such as J-Integra and Mark Hammond's libraries. How would you do this if you want a mechanism that is portable across Windows, Linux, Mac, and Unix? Any ideas? Jython would be a natural candidate, but it is stuck at Python 2.1 and seems to have an uncertain future. Thanks in advance. From kent at kentsjohnson.com Fri Mar 31 05:48:44 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 31 Mar 2006 05:48:44 -0500 Subject: How to debug python code? In-Reply-To: <1143782330.199836.221880@v46g2000cwv.googlegroups.com> References: <1143782330.199836.221880@v46g2000cwv.googlegroups.com> Message-ID: <442d03ca_1@newspeer2.tds.net> sushant.sirsikar at gmail.com wrote: > hi, > I am new to Python programming.I am not getting exactly pdb.Can > anyone tell me effective way to debug python code? I too rely mostly on unit tests and print statements for debugging, but occasionally I use winpdb which is a pretty nice GUI debugger. http://www.digitalpeers.com/pythondebugger/ Kent From hanumizzle at gmail.com Fri Mar 17 20:16:02 2006 From: hanumizzle at gmail.com (hanumizzle at gmail.com) Date: 17 Mar 2006 17:16:02 -0800 Subject: Very, Very Green Python User In-Reply-To: <4418b02d$0$1078$636a55ce@news.free.fr> References: <1142215118.291132.130490@e56g2000cwe.googlegroups.com> <44172c5b$0$2083$626a54ce@news.free.fr> <1142451318.927076.79310@e56g2000cwe.googlegroups.com> <4418b02d$0$1078$636a55ce@news.free.fr> Message-ID: <1142644562.395944.204780@z34g2000cwc.googlegroups.com> Dhanyavaad (thank you) From aisaac0 at verizon.net Sat Mar 25 10:55:26 2006 From: aisaac0 at verizon.net (David Isaac) Date: Sat, 25 Mar 2006 15:55:26 GMT Subject: Comparisons and singletons References: <1143283477.483035.212980@v46g2000cwv.googlegroups.com> Message-ID: "Ziga Seilnacht" wrote in message news:1143283477.483035.212980 at v46g2000cwv.googlegroups.com... > >>> a = 10000 > >>> b = 10000 > >>> a == b > True > >>> a is b > False Two follow up questions: 1. I wondered about your example, and noticed >>> a = 10 >>> b = 10 >>> a is b True Why the difference? 2. If I really want a value True will I ever go astray with the test: if a is True: >>> a = True >>> b = 1. >>> c = 1 >>> a is True, b is True, c is True (True, False, False) Thanks, Alan Isaac From sathyaish at gmail.com Tue Mar 28 09:29:45 2006 From: sathyaish at gmail.com (Sathyaish) Date: 28 Mar 2006 06:29:45 -0800 Subject: in-place string reversal In-Reply-To: References: <1143554931.104392.187480@i39g2000cwa.googlegroups.com> Message-ID: <1143556185.348035.254900@t31g2000cwb.googlegroups.com> >But what's got that to do with it? Strings are very mutable in C. I realized after posting that I'd said something incorrect again. The concept of "mutability" itself is a high-level concept compared to C. Memory allocation for strings is expensive because of the way malloc() works to find a "best-fit" against a "first-fit" in traditional memory management systems. Because of the performance hit, high level languages and frameworks, such as the Common Type System of the .NET Framework for example, considers strings as immutable. That, unlike Python, doesn't however, make them impossible to modify in-place. From hanumizzle at gmail.com Wed Mar 15 13:58:26 2006 From: hanumizzle at gmail.com (hanumizzle at gmail.com) Date: 15 Mar 2006 10:58:26 -0800 Subject: Very, Very Green Python User In-Reply-To: References: <1142215118.291132.130490@e56g2000cwe.googlegroups.com> Message-ID: <1142449106.619539.254940@e56g2000cwe.googlegroups.com> Dennis Lee Bieber wrote: > On 12 Mar 2006 17:58:43 -0800, hanumizzle at gmail.com declaimed the > following in comp.lang.python: > > > > > Double-underscore methods are rewritten with the class name? That's an > > ugly hack, but remember I'm coming from Perl. If the language doesn't > > pull many other hijinks, that's OK. > > > Compared to a language that added OO by requiring the user to > "bless" things to make it behave as an object, you find name-mangling > for "private" methods to be ugly? I saw the duplicity in my own post; mai ben rai. :D > I suggest you never look under the hood of a C++ compiler...They > not only name-mangle, but add such crud as type/size codes for arguments > and return value -- all to be able to invoke the correct method due to > overloading. I've heard about the brain damages of C++. Never programmed in it; don't need to. If I were ever forced to program C++ as a result of a career, I think I would probably quit. From fredrik at pythonware.com Wed Mar 8 09:41:31 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 8 Mar 2006 15:41:31 +0100 Subject: Having to "print" before method invocation? References: <1141828148.1863.9.camel@localhost.localdomain> Message-ID: Jeremy L. Moles wrote: >I have an object (written as part C extension, part pure Python) called > foo that I've been using without much fuss for a few months now. > However, in my latest project (a rather large one involving > multi-threading, pygtk, etc.), I'm seeing some really strange behavior > with a particular instance of my foo object. > > About midway through my program, any attempt to use the instance fails; > however, if I add print statements before trying to invoke methods on > it, the foo object instance works fine. fails in what way? if you get a spurious exception, it's very likely that your C extension sets the exception state (either directly or because some API function it uses fails), but forgets to report this back to Python. e.g. if you have a C function that does something like PyErr_SetString(PyExc_AttributeError, "blah blah"): Py_INCREF(Py_None); return Py_None; instead of PyErr_SetString(PyExc_AttributeError, "blah blah"): return NULL; the interpreter won't raise the exception immediately (since it expected you to return NULL if something went wrong), but the exception may still be raised at a later time, if you run interpreter code that does something like do something if (PyErr_Occurred()) ... /* this will catch your error even if "something" succeeds */ ... *or* it may be masked, by code that does PyErr_Clear(); do something the actual exception might give you additional clues (e.g. if you get a KeyError, look for unchecked dictionary accesses in your code, etc). hope this helps! From eurleif at ecritters.biz Wed Mar 1 19:31:02 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 01 Mar 2006 19:31:02 -0500 Subject: Proper class initialization In-Reply-To: References: Message-ID: <44063c9f$0$25069$4d3efbfe@news.sover.net> Steven Bethard wrote: > class A(object): > def _get_sum(): > return sum(xrange(10)) > sum = _get_sum() What's wrong with sum = sum(xrange(10))? From i.failed.turing.test at gmail.com Sat Mar 4 22:18:40 2006 From: i.failed.turing.test at gmail.com (David Treadwell) Date: Sat, 4 Mar 2006 22:18:40 -0500 Subject: Python advocacy in scientific computation In-Reply-To: References: Message-ID: On Mar 4, 2006, at 11:16 PM, Dennis Lee Bieber wrote: > On Sat, 4 Mar 2006 14:23:10 -0500, David Treadwell > declaimed the following in > comp.lang.python: > >> needed programming, be it CS or chemical engineering, taught it in >> a wlfraed at ix.netcom.com >> very linear, bottom-up fashion. First you read inputs, then do Foo, >> then do Bar, then do (fill in your favorite third-level word). >> > Doesn't quite sound like what was "bottom up" in my day... Sounds > like an common "input, process, output" design. Well, you're right about my description--that's what the program ended up looking like. It wasn't the way it was written. Usually, I'd do it more like this: Find or derive the formula of interest. Translate the formula into ForTran (hmmm ... catchy name for a language!) Put the minimum number of statements around the formula to get it to run. Write the UI. Back in the day, a user interface consisted of $ENTRY ... or 9999 DATA ... or, if we were feeling lucky, READ (6,*) ... (or whatever) By the time I finished writing the code, if I was lucky, it looked like what I described. Very few subroutines (Maybe some LINPAC or some other code package), lots of the dreaded GOTO statements. Comment statements? A waste of punch cards and RAM. *LOL* Then spend weeks squashing bugs. Shells, wrappers, IF...THEN...ELSE blocks, code with only one input and one output were concepts unknown to us. To put it mildly, I feel very under-served by my formal computer education. Perhaps it was just a matter of bad timing. Still, as one post said, they teach us 8 semesters of mathematics and one of Fortran, expecting us to learn how to program by ourselves. Pick up any older book on "Numerical Methods in the Foo Sciences". They got the numbers crunched, but the programming style was wretched. Donald Knuth, were were you? > "Bottom up", to me, was more: write the code to read/write the data > records; then use those routines to write code to modify the > contents of > the records; repeat ad infinitum (it seemed) until you reached the > main > program -- which sort of came down to a "fiat lux". > > "Top down/Functional decomposition" ran the other way... Start with > the main program. Determine what major activities it has to > perform, and > add invocations to stub routines for each of those. Repeat with each > stub, add invocations to the stubs for the functions it had to > perform... until you reach the layer that does the "physical work", > say... Problem with this approach, especially in a poorly thought out > team, is that you may have widely spaced sections that have to > manipulate the same file, say -- and end up with multiple routines all > incompatible to do that. Been there, done that. Aren't XML and the other structured data protocols nice? > > Often I'd (on solo efforts) get to some point, and then reverse, to > build the low-level routines as a library... I think I've heard that > defined as "outside in" design. Sometimes, I'd add so many layers of crud onto the original meat of the program, it was just easier to toss the whole thing out. What a royal waste of time. Far better to plan ahead. > > In one aspect, OOP is closer to the "bottom up" approach, since one > is creating "objects" to represent/manipulate the same things one > started with in "bottom up"; just better encapsulated -- you don't > suddenly find some routine 10 layers up that is directly manipulating > the data (object state) with no direct understanding of where this > data > came from, where it is going, etc. Yes, but the computer doesn't, and never did "understand" the data. All of this OOP stuff was invented to help the Programmer and Legacy Code Maintainers understand the processing. > In my college, it was the business majors that got hit... The > Statistics II course was 90% number crunching using a statistics > package > (I've forgotten the name of the package -- its been 27 years; and as a > CS major I only had to take Stat I... SPSS comes to mind: Statistical > Package for the Social Sciences). And COBOL. Even in 1977, I used to feel sorry for the people who had to program in COBOL. > > Database management was worse: at the time, my textbook went > "Hierarchical, Network, (theoretical) Relational" (five years later, a > new edition went "Relational, (historical) Network, (historical) > Hierarchical". Campus mainframe ran a DBTG Network model DBMS. As a general rule, the scientists and engineers I know can't understand the structure of a database that doesn't fit into MS Excel. > >> >> I still don't get OOP completely, but Python has helped a great deal. >> > I'm still terrible with the more intangible "objects", and various > inheritance concerns... I do much better when the "objects" > directly map > to tangible things (it is easy to model a radio: components include > things like "tuner", "audio amplification", "demodulator/mixer") -- > but > trying to visualize a broadcast received on that radio as an > "object" is > not so easy. And this is after having taken a few OOA/OOD courses. I can't wait to need that kind of stuff. I think I'm baffled now... >> Sure. It seems logical now. But remember, I learned WatFiv Fortran, >> which came before even Fortran 77. I saw my first Fortran 95 code >> about two years ago. It took me a while to realize that what I was >> looking at _was_ Fortran! >> > F90/F95 is scary, isn't it... > > F77 wasn't that big a change from FORTRAN-IV (F66) (hmmm, we're due > for another standard, aren't we? 1966, 1977, 1990 [95 was a tweak]...) Shouldn't Fortran 2003 be out by now? Maybe it will be so great that Python 3.x will be written completely in it? FPython, ayone? > > The major things F77 added were: a string type, consolidation of I/O > such that encode()/decode() weren't needed, and blocked IF/ELSE > statements. I made the mistake of using the word "Hollerith" in front of a 21 y.o. CS grad. I had to explain the history of the punch card. >> Google makes this game too easy, but it's to Who you refer. How about >> _this_ reference: "What we all need is a left-handed monkey wrench." > > Since I'm not going to Google it, I'll have to pass. > {I'll also have to set up a recorder for March 17, SciFi Channel} The Grateful Dead paying homage to a time-honored Navy tradition. Is the SciFi Channel having a Who-fest? :--David From mtobis at gmail.com Sat Mar 11 13:04:58 2006 From: mtobis at gmail.com (Michael Tobis) Date: 11 Mar 2006 10:04:58 -0800 Subject: Cheese Shop -> BSOL? In-Reply-To: References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> <1142039514.707128.240270@j33g2000cwa.googlegroups.com> Message-ID: <1142100298.930300.132420@u72g2000cwu.googlegroups.com> I like cheeseshop just fine, but have been a Monty Python fan since they appeared on the CBC in, I think, 1969. I'm one of those people who is always surprised when a MP bon mot is greeted with confusion and the suspicion that I have finally lost my mind altogether. So... If we are moving to the snake motif (which probably would be better marketing): "Pythons lay eggs which they arrange in a pile. They coil around the pile until all eggs have hatched. Since pythons cannot regulate their internal body temperature, they cannot incubate their eggs per se; instead, they raise the temperature of their eggs by small movements of their body-essentially, they "shiver". This is one of only a few documented cases of parental behaviour in snakes." --Wikipedia article "python" Pythons build no nests. Their eggs are found in coils. coil.python.org ? Tadpoles ( http://python.org/images/python-logo.gif ) are immature frogs. If we keep the logo, we can change the name of the language to "frog". Then the eggs would be found in lilypad.frog.org . I personally do not like this choice but it would have the virtue of consistency. (Did I mention that I don't like the logo?) mt From laurent.pointal at limsi.fr Fri Mar 31 05:19:58 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 31 Mar 2006 12:19:58 +0200 Subject: Connecting to gnuplot with Popen? In-Reply-To: References: Message-ID: Anton81 a ?crit : > Hi, > > it seems to be a FAQ, but I still haven't found a solution. I want to > control gnuplot with a python program. The following at least gives me the > gnuplot output: Unless you absolutely need to write your own code, you should try: http://gnuplot-py.sourceforge.net/ A+ Laurent. From jparlar at cogeco.ca Tue Mar 7 02:50:36 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Mon, 6 Mar 2006 23:50:36 -0800 Subject: Checking function calls In-Reply-To: References: Message-ID: <814a390724682d39f52c2528b8c0d830@cogeco.ca> On Mar 6, 2006, at 8:44 PM, James Stroud wrote: > Since python is "weakly typed", you will not be able to check what > "type" of arguments a function expects. TypeErrors relating to the > type of argemtns you pass will be raised inside the function only and > not when it is called. I.e. there is no type checking when a function > is called, only in its body. > I don't mean to take a tangent from the original purpose of the thread, but it is generally accepted that Python is STRONGLY, dynamically typed. An example of weak dynamic typing would be Perl. A lot of it of course comes down to one's definitions of strong/weak, but general consensus (at least around c.l.p.) is that Python is a strongly typed language. Jay P. From antroy at gmail.com Tue Mar 21 04:10:19 2006 From: antroy at gmail.com (Ant) Date: 21 Mar 2006 01:10:19 -0800 Subject: Python 2.5 Schedule References: <1142667600.257048.315910@z34g2000cwc.googlegroups.com> Message-ID: <1142932219.908449.315920@g10g2000cwb.googlegroups.com> Looks like some good new stuff coming along. Does anyone know what's happened to the path PEP (http://www.python.org/doc/peps/pep-0355/) - I thought I'd seen somewhere that that was originally planned for 2.5... -- Ant... From fredrik at pythonware.com Fri Mar 31 01:40:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 31 Mar 2006 08:40:39 +0200 Subject: any() and all() on empty list? References: <442B9AF7.2010407@REMOVEMEcyber.com.au><7xu09gicko.fsf@ruckus.brouhaha.com><442BAAA5.8010009@REMOVEMEcyber.com.au><491ne1Fm9stiU1@individual.net> <1hd17wl.18u0c9n1y5g7mgN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > > >>>all(flying elephants which are not pink) => true > > >>> > > >>>So, these flying elephants -- are they pink or not? > > >> > > >> No, you ask two different sets whether they are true. > > > > > > No, there is only one empty set. > > > > who said anything about empty sets ? > > Universally-false predicate <--> empty set > > ...in Cantor's/Frege's world I was more thinking of Disney. From bapolis at gmail.com Wed Mar 1 06:32:47 2006 From: bapolis at gmail.com (bapolis at gmail.com) Date: 1 Mar 2006 03:32:47 -0800 Subject: pysqlite problem In-Reply-To: <1141212172.445009.230610@i39g2000cwa.googlegroups.com> References: <1141212172.445009.230610@i39g2000cwa.googlegroups.com> Message-ID: <1141212767.539481.53270@t39g2000cwt.googlegroups.com> my bad. that was the wrong code, here is my code: from pysqlite2 import dbapi2 as sqlite con = sqlite.connect("ex1") cur = con.cursor() cur.execute("select * from tbl1") print cur.fetchall() From johnjsal at NOSPAMgmail.com Sat Mar 25 15:25:57 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 25 Mar 2006 15:25:57 -0500 Subject: a somewhat off-topic question about linux In-Reply-To: References: <_oedne4wPJ9DPrjZnZ2dnUVZ_tWdnZ2d@rcn.net> Message-ID: <6LidnQr7npY-OrjZnZ2dneKdnZydnZ2d@rcn.net> Christoph Haas wrote: > On Sat, Mar 25, 2006 at 03:09:53PM -0500, John Salerno wrote: >> I'm interested in trying out Linux, probably Ubuntu, but I was wondering >> which distribution you guys like to use (because it's a pain trying to >> decide!) and you guys are smart. > > We had this discussion a couple of time during the last months already. :) > I believe the most frequently recommended distribution was Ubuntu (or > Debian which Ubuntu is based upon). Oh sorry! I should have checked first. And yeah, I don't mean to start a big argument about which is better... :) But thanks for the answer. I'm comforted to know that my choice is a good one. And as for Python, as long as there are no surprises, I should be okay. From rory at campbell-lange.net Thu Mar 2 06:12:41 2006 From: rory at campbell-lange.net (Rory Campbell-Lange) Date: Thu, 2 Mar 2006 11:12:41 +0000 Subject: Newbie errors :-( Need help In-Reply-To: <20060302110145.73025.qmail@web34601.mail.mud.yahoo.com> References: <20060302110145.73025.qmail@web34601.mail.mud.yahoo.com> Message-ID: <20060302111241.GA26536@campbell-lange.net> There is no variable called result in your function or, presumably, in the global scope of the programme. As you aren't returning anything you may as well omit that line. On 02/03/06, - C Saha - (p4sync at yahoo.com) wrote: > I am getting the result but along with this error, any idea what could be the reason? > > fibo.fib(1000) > 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987Traceback (most recent call last): > File "", line 1, in ? > File "fibo.py", line 8, in fib > return result > NameError: global name 'result' is not defined -- Rory Campbell-Lange From steve at hastings.org Wed Mar 29 00:32:51 2006 From: steve at hastings.org (Steve R. Hastings) Date: Tue, 28 Mar 2006 21:32:51 -0800 Subject: any() and all() on empty list? Message-ID: So, Python 2.5 will have new any() and all() functions. http://www.python.org/dev/peps/pep-0356/ any(seq) returns True if any value in seq evaluates true, False otherwise. all(seq) returns True if all values in seq evaluate true, False otherwise. I have a question: what should these functions return when seq is an empty list? Here is Guido's original article where he suggested any() and all(): http://www.artima.com/weblogs/viewpost.jsp?thread=98196 He offered this sample code for the semantics of any() and all(): def any(S): for x in S: if x: return True return False def all(S): for x in S: if not x: return False return True And he pointed out how nifty it is to combine generator functions with these two new functions: any(x > 42 for x in S) # True if any elements of S are > 42 all(x != 0 for x in S) # True if all elements if S are nonzero I'm completely on board with the semantics for any(). But all() bothers me. If all() receives an empty list, it will return True, and I don't like that. To me, all() should be a more restrictive function than any(), and it bothers me to see a case where any() returns False but all() returns True. In the all() example, if there *are* no values in S, then none of the values can be != 0, and IMHO all() should return False. Therefore, I propose that all() should work as if it were written this way: def all(S): ret_val = False for x in S: ret_val = True if not x: return False return ret_val Comments? P.S. I searched with Google, and with Google Groups, trying to find anyplace this might have been discussed before. Apologies if this has already been discussed and I missed it somehow. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From programmer.py at gmail.com Fri Mar 10 15:49:29 2006 From: programmer.py at gmail.com (programmer.py at gmail.com) Date: 10 Mar 2006 12:49:29 -0800 Subject: epydoc help (putting XML in docstrings) Message-ID: <1142023769.899027.114920@j33g2000cwa.googlegroups.com> Hi everyone! I'm documenting some functions that return XML strings. I'd like to have `sample' xml show up in my epydoc generated documentation. However, epydoc does not like the indentation of the XML and gives me this error -> L28: Error: Improper paragraph indentation. Here is a simple function that epydoc does not like: def test(): """ Return an XML string that looks like this:: 123 D ... @return: XML string. """ pass [jwyant at L-JWYANT:daplib]$ epydoc test.py Importing 1 modules. [.] Building API documentation for 1 modules. [.] =========================================================================== C:\cygwin\home\jwyant\code\dap-support\python\daplib\test.py In test.test docstring (line 2): --------------------------------------------------------------------------- L5: Error: Improper paragraph indentation. Any ideas? Thanks! From seb.haase at gmail.com Tue Mar 28 12:32:10 2006 From: seb.haase at gmail.com (seb.haase at gmail.com) Date: 28 Mar 2006 09:32:10 -0800 Subject: pickle: 32bit vs 64bit Message-ID: <1143567130.660752.33560@v46g2000cwv.googlegroups.com> Hi, I have ordered a new Athlon64 PC running linux x86_64. I'm using Pyro to communicate between python programs running on different machines. I know that, because Pyro's communication is based on pickle, that the different machines have to run the same Python (major) version: that is, it did not work after I just upgraded ONE machine from Py2.2 to Py2.4. How will this be when all machines run Python2.4, but one will be compiled as a 64bit application, the others 32bit ? (If it works for 2.4, will it still work for Python2.5, where lists can be larger than 2GB ONLY on 64bit-Python ? [of course I mean the case where the lists are actually (much) shorter than 2GB !!] ) Thanks, Sebastian Haase From kent at kentsjohnson.com Mon Mar 27 15:46:24 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 27 Mar 2006 15:46:24 -0500 Subject: pysqlite In-Reply-To: <44284677$1_3@newspeer2.tds.net> References: <1143483441.697284.206720@u72g2000cwu.googlegroups.com> <1143484790.996231.232000@j33g2000cwa.googlegroups.com> <44284677$1_3@newspeer2.tds.net> Message-ID: <442849f0_1@newspeer2.tds.net> Kent Johnson wrote: > abcd wrote: > >>>>anyone have v2.x of pysqlite that I could download? the website is >>>>down for a hardware upgrade with no date as to when it will be back. >>>> >>> >>I need v 2.x for windows, running python v2.4 > > > I sent pysqlite-2.0.4.win32-py2.4.exe Well tried, anyway, someone between OP and me is blocking zip and exe attachements. Kent From rrr at ronadam.com Sun Mar 19 19:37:39 2006 From: rrr at ronadam.com (Ron Adam) Date: Sun, 19 Mar 2006 18:37:39 -0600 Subject: Is there such an idiom? In-Reply-To: <1142813592.486643.111550@j33g2000cwa.googlegroups.com> References: <1142813592.486643.111550@j33g2000cwa.googlegroups.com> Message-ID: Per wrote: > http://jaynes.colorado.edu/PythonIdioms.html > > """Use dictionaries for searching, not lists. To find items in common > between two lists, make the first into a dictionary and then look for > items in the second in it. Searching a list for an item is linear-time, > while searching a dict for an item is constant time. This can often let > you reduce search time from quadratic to linear.""" > > Is this correct? > s = [1,2,3,4,5...] > t = [4,5,6,,8,...] > how to find whether there is/are common item(s) between two list in > linear-time? > how to find the number of common items between two list in linear-time? I'm not sure if it works in linear time, but if there are no duplicates in each list, sets would be the easiest way to do these with. >>> s = set([1,2,3,4,5,6]) >>> t = set([4,5,6,7,8,9]) >>> s.intersection(t) set([4, 5, 6]) >>> len(s.intersection(t)) 3 Cheers, Ron From nun at example.com Fri Mar 3 14:17:01 2006 From: nun at example.com (Mitja Trampus) Date: Fri, 03 Mar 2006 20:17:01 +0100 Subject: help in converting perl re to python re In-Reply-To: References: <1141369650.346212.321410@i40g2000cwc.googlegroups.com> Message-ID: >> i have some regular exp code in perl that i want to convert to python. >> if $line =~ m#<(tag1)>(.*)# >> { >> $variable = $2; >> } > regexp = re.compile(r"<(tag1)>(.*)") > line = "sometext" > match = regexp.search(line) > if match: > variable = match.group(2) Or, if you prefer shorter, quick-and-dirty syntax closer to perl's approach: match = re.search(r"<(tag1)>(.*)", line) if match: variable = match.group(2) From chris.eder at gmx.at Thu Mar 23 13:30:22 2006 From: chris.eder at gmx.at (Christian Eder) Date: Thu, 23 Mar 2006 19:30:22 +0100 Subject: Strange metaclass behaviour In-Reply-To: <1143127358.820526.259930@i40g2000cwc.googlegroups.com> References: <1143127358.820526.259930@i40g2000cwc.googlegroups.com> Message-ID: <1143138624.25186@news.aic.at> Michele Simionato wrote: > Still, it is an interesting exercise if you are willing to risk the > melting of your brain, > so here is the code ;) I tried your code and it fixes the double execution, but the __new__ is executed in context of M_A instead of M_B which would be the more specific type here. Anyway, I think I found an acceptable solution for the problem. The question is "What Do I need to fix metaclasses ?" And the answer, of course, is "a meta-meta-class !" The following code solves the problem. It's basically Ziga's code except that I added one level of abstraction (to avoid adding this kludge code to each custom metaclasses'es __new__): class _fixed_type_ (type) : def __call__ (meta, name, bases, dict) : meta = meta._get_meta (bases, dict) cls = meta.__new__ (meta, name, bases, dict) meta.__init__ (cls, name, bases, dict) return cls # end def __call__ def _get_meta (meta, bases, dict) : if "__metaclass__" in dict : return dict ["__metaclass__"] winner = meta for b in bases : cand = type (b) if cand in (types.ClassType, type) : pass elif issubclass (cand, winner) : winner = cand elif issubclass (winner, cand) : pass else : raise TypeError ("Metatype conflict among bases") return winner # end def _get_meta # end class _fixed_type_ class my_type (type) : __metaclass__ = _fixed_type_ ### to fix metaclasses, we need ### meta-meta classes # end class my_type Then I made "my_type" the root of my metaclass hierarchy (instead of "type") which solves all my problems. After 5 years of Python, I still find it impressive how much vodoo and mojo one can do here :-) regards chris From snail at objmedia.demon.co.uk Wed Mar 15 05:18:01 2006 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Wed, 15 Mar 2006 10:18:01 +0000 Subject: Memory visualization References: <1142318282.330669.129630@z34g2000cwc.googlegroups.com> Message-ID: <8OxXkGCZn+FEFwEp@objmedia.demon.co.uk> In message , Tim Peters writes >[bearophileHUGS at lycos.com] >> I'd like to know if for Python there is a similar program to >> dynamically see the memory in a similar way. >> If such tool doesn't exist yet, I'd like to know if it may be diffifult >> to create it. One already exists: Python Memory Validator. Software Verification provide software tools for Python on the Windows platform. Software Verification have two commercial products for coverage and performance profiling and three beta products for flow tracing, memory analysis and thread deadlock monitoring. http://www.softwareverify.com Software Verification run with Python 2.2 upwards - no need to modify the python source or binary. 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 steve at holdenweb.com Mon Mar 20 07:40:45 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 20 Mar 2006 12:40:45 +0000 Subject: Chained Comparisons In-Reply-To: <1142857406.976214.249060@g10g2000cwb.googlegroups.com> References: <1142835847.348629.177950@z34g2000cwc.googlegroups.com> <441e607d$1@news.eftel.com> <1142842595.057727.298380@z34g2000cwc.googlegroups.com> <1142854054.652447.66120@z34g2000cwc.googlegroups.com> <1142857406.976214.249060@g10g2000cwb.googlegroups.com> Message-ID: Sathyaish wrote: > Thanks, Peter. I do use the interpreter alongside while reading the > documentation and also try out the examples. It was just a matter of > chance that for this particular situation, I did not. > > Thank you for the answers, everyone. I hope I am still welcome here for > more questions. > Absolutely no reason why not. You'll be answering them before long. Welcome to c.l.py. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From sjw28 at sussex.ac.uk Mon Mar 6 10:03:24 2006 From: sjw28 at sussex.ac.uk (nuttydevil) Date: 6 Mar 2006 07:03:24 -0800 Subject: processing the genetic code with python? Message-ID: <1141657404.593850.151930@e56g2000cwe.googlegroups.com> I have many notepad documents that all contain long chunks of genetic code. They look something like this: atggctaaactgaccaagcgcatgcgtgttatccgcgagaaagttgatgcaaccaaacag tacgacatcaacgaagctatcgcactgctgaaagagctggcgactgctaaattcgtagaa agcgtggacgtagctgttaacctcggcatcgacgctcgtaaatctgaccagaacgtacgt ggtgcaactgtactgccgcacggtactggccgttccgttcgcgtagccgtatttacccaa Basically, I want to design a program using python that can open and read these documents. However, I want them to be read 3 base pairs at a time (to analyse them codon by codon) and find the value that each codon has a value assigned to it. An example of this is below: ** If the three base pairs were UUU the value assigned to it (from the codon value table) would be 0.296 The program has to read all the sequence three pairs at a time, then I want to get all the values for each codon, multiply them together and put them to the power of 1 / the length of the sequence in codons (which is the length of the whole sequence divided by three). However, to make things even more complicated, the notebook sequences are in lowercase and the codon value table is in uppercase, so the sequences need to be converted into uppercase. Also, the Ts in the DNA sequences need to be changed to Us (again to match the codon value table). And finally, before the DNA sequences are read and analysed I need to remove the first 50 codons (i.e. the first 150 letters) and the last 20 codons (the last 60 letters) from the DNA sequence. I've also been having problems ensuring the program reads ALL the sequence 3 letters at a time. I've tried various ways of doing this but keep coming unstuck along the way. Has anyone got any suggestions for how they would tackle this problem? Thanks for any help recieved! From mutantwebdesign at gmail.com Mon Mar 20 02:22:24 2006 From: mutantwebdesign at gmail.com (mutant) Date: 19 Mar 2006 23:22:24 -0800 Subject: Free Blog Hosting Message-ID: <1142839344.901730.192280@u72g2000cwu.googlegroups.com> Hi, I setup an account at http://www.bloggerteam.com the site provides quality blog hosting services with quality editable templates, google sitemaps built in and many more features. Also subdomain style urls which are easy remembered by your friends and familes. If you love blogging that try this service it is nice and cool templates are the major attraction. Regards. From fredrik at pythonware.com Fri Mar 3 09:52:14 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 3 Mar 2006 15:52:14 +0100 Subject: Convert dictionary to HTTP POST References: <4408084D.4060708@designaproduct.biz> <4408493C.8050901@designaproduct.biz> Message-ID: Laszlo Zsolt Nagy wrote: > The values of some inputs are encoded using html entities. > How can I decode a string like "Bessy's cat" in "Bessy's cat"? this snippet might help: http://effbot.org/zone/re-sub.htm#strip-html From rNOSPAMon at flownet.com Mon Mar 13 12:56:30 2006 From: rNOSPAMon at flownet.com (Ron Garret) Date: Mon, 13 Mar 2006 09:56:30 -0800 Subject: Is this possible in Python? References: <1142238871.199749.243470@p10g2000cwp.googlegroups.com> Message-ID: In article <1142238871.199749.243470 at p10g2000cwp.googlegroups.com>, alainpoint at yahoo.fr wrote: > Hi > > I wonder if Python is capable of the following: define a function which > returns its argument. > I mean: > def magic_function(arg): > ...... some magic code ... > > that behaves the following way: > > assert magic_function(3+4)=="3+4" > assert magic_function([i for i in range(10)])=="i for i in range(10)]" > > It is not trivial at all and might require some bytecode hacking that i > am unable to do myself BUT you are the experts ;-) > > Alain You probably want to learn Lisp, where what you want to do is trivial: (defmacro magic (arg) arg) rg From cgseymour at gmail.com Wed Mar 29 13:06:54 2006 From: cgseymour at gmail.com (Chris Seymour) Date: 29 Mar 2006 10:06:54 -0800 Subject: Quick Question regarding Frames In-Reply-To: <1143654936.844212.283780@i40g2000cwc.googlegroups.com> References: <1143555706.435922.309210@g10g2000cwb.googlegroups.com> <1143571941.731740.228960@g10g2000cwb.googlegroups.com> <1143577846.750248.107300@j33g2000cwa.googlegroups.com> <1143654936.844212.283780@i40g2000cwc.googlegroups.com> Message-ID: <1143655614.211630.148110@z34g2000cwc.googlegroups.com> Hi Dave, Thanks for taking the time to reply to my posts. It really heped me understand this better. Thanks again. Chris From aleaxit at yahoo.com Sun Mar 5 10:54:53 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Mar 2006 07:54:53 -0800 Subject: Inline assignments References: Message-ID: <1hbptv8.tiu98s1inl20sN%aleaxit@yahoo.com> Fredrik Tolf wrote: ... > I'm relatively new to Python, and one thing I can't seem to get over is > the lack of in-expression assignments, as present in many other > languages. I'd really like to know how Python regulars solve the > problems posed by that. In general, we've learned to do without and structure our code differently -- less compactly, more "airy". Python is not about maximally compact code -- other languages of roughly equivalent power, such as Perl, are more suitable if that's your goal; in Python, we aim for less compactness and more readability (and maintainability). E.g.: > if callable(f = getattr(self, "cmd_" + name)): > # Do something with f > elif callable(f = getattr(self, "cmdv_" + name)): > # Do something else with f might become: f = getattr(self, "cmd_" + name) if callable(f): # Do something with f else: f = getattr(self, "cmdv_" + name) if callable(f): # Do something else with f 7 lines instead of 4 (if the comments stand for one line each), but exactly the same semantics. > Another common problem for me are while loops. I would often like to do That's part of why Python often prefers for loops -- with a generator to handle the "looping logic" part, if needed. For example, > while (pos = somestring.find("/")) != -1: > part = somestring[:pos] > somestring = somestring[pos + 1:] > # Handle part might often become a simple: for part in somestring.split('/'): # handle part but that has slightly different semantics (handles the part after the last occurrence of / too, doesn't explicitly record pos, ...) which might be adjusted if needed (e.g. with a [:-1] after the call to split and before the colon to omit the last part). If the adjustment is "major", e.g. you do need every variable to be set just like so in the body, then a generator can help -- with the focus being on a separation between the business logic (the "handle part" processing) and the plumbing (generate all 'parts' in sequence), and the latter going in the generator, not distracting from the handling as may happen when you mix the two things. The business-logic part will always look like: for pos, part in splitter(somestring, '/'): # handle part, using pos as well and the splitter generator is written elsewhere, a la def splitter(somestring, separ): while True: pos = somestring.find(separ) if pos == -1: break yield pos, somestring[:pos] somestring = somestring[pos+1:] with the big advantage that you may change the implementation to be more efficient, if and when needed, without touching the business logic part which remains nestled in the nice, simple, readable for loop. for example: def splitter(somestring, separ): pos = 0 while True: nextpos = somestring.find(separ, pos) if nextpos == -1: break yield nextpos-pos, somestring[pos:nextpos] pos = nextpos+1 Same semantics, less busywork, so presumably faster (the timeit module exists to let you check the speed of code fragments, of course). All this being said, I do sometimes find myself coding a first version of some algorithm by following as closely as possible some published reference code or pseudocode, before enhancing it to be clearer, more efficient, more Pythonic, or whatever. When that happens, some syntax sugar to "assign and test in the same expression" does come in handy, to enable coding of a first version that's closer in spirit to the non-Python reference version. It was, of course, no trouble at all to make myself an "assign and test in the same expression" snippet, and I (again, of course) published it in the Python Cookbook (both online and printed editions) for others' benefit. For example: class Holder(object): def set(self, value): self.value = value return value data = Holder() Now, with this tiny piece of "plumbing adapter", you can code, e.g.: while data.set(somestring.find("/")) != -1: part = somestring[:data.value] somestring = somestring[data.value + 1:] # Handle part Another use case for this Holder class is when you're using Python to prototype something that you already know will need to be recoded in another given language once it's ready -- the motivation is similar to the one for the main use case of "code as close as possible to a published reference implementation", namely enabling Python code that is closer to what's idiomatic in some other language than to idiomatic Python itself. Therein, of course, lies the danger -- over-relying on this adapter may mean you never really learn to "think the Python way" and thus to code idiomatic Python, even when that would be most appropriate (i.e., in most cases). Still, Python _is_ a "consenting adults" language, so I think it's appropriate to show how its power can easily let you keep using idioms coming from different languages... even when that usage is not the optimal choice that you could and should make, it's up to you. Alex From onurb at xiludom.gro Wed Mar 22 10:38:49 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 22 Mar 2006 16:38:49 +0100 Subject: Per instance descriptors ? In-Reply-To: <1143038744.159609.104460@g10g2000cwb.googlegroups.com> References: <44211ee8$0$7890$636a55ce@news.free.fr> <1143038744.159609.104460@g10g2000cwb.googlegroups.com> Message-ID: <44216fc5$0$26190$626a54ce@news.free.fr> Ziga Seilnacht wrote: > bruno at modulix wrote: > >>Hi >> >>I'm currently playing with some (possibly weird...) code, and I'd have a >>use for per-instance descriptors, ie (dummy code): > > > > >>Now the question: is there any obvious (or non-obvious) drawback with >>this approach ? > > > Staticmethods won't work anymore: > > >>>>class Test(object): > > ... @staticmethod > ... def foo(): > ... pass > ... def __getattribute__(self, name): > ... v = object.__getattribute__(self, name) > ... if hasattr(v, '__get__'): > ... return v.__get__(self, self.__class__) > ... return v > ... > >>>>test = Test() >>>>test.foo() > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: foo() takes no arguments (1 given) > Hmmm.... Well, I almost never use staticmethods, but I need to check this out. (a few minutes later) Ok, no apparent impact on classmethods. For staticmethod, a quick fix is: import types > ... def __getattribute__(self, name): > ... v = object.__getattribute__(self, name) > ... if not isinstance(v, types.FunctionType) \ and hasattr(v, '__get__'): > ... return v.__get__(self, self.__class__) > ... return v Thanks Ziga. Anyone else ? Any good reason to *not* do this ? Or is presumably safe ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From eddie at holyrood.ed.ac.uk Wed Mar 29 07:06:05 2006 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Wed, 29 Mar 2006 12:06:05 +0000 (UTC) Subject: telnet session References: <1143632572.802412.6070@z34g2000cwc.googlegroups.com> Message-ID: eight02645999 at yahoo.com writes: >hi >i am using a telnet session to simulate an authentication mechanism >USER = "user" >PASSWORD = "password" >try: > telnet = telnetlib.Telnet(HOST) > telnet.set_debuglevel(5) > telnet.read_until("login: ") > telnet.write(USER + "\n") > telnet.read_until("Password: ") > telnet.write(PASSWORD + "\n") >except: > print "failed to telnet" >else: > try: > telnet.write("ls\n") > except: > print "cannot ls" > else: > telnet.write("exit\n") > print telnet.read_all() >When i purposely input a wrong password, it "hangs" at the login prompt >waiting for >login and Password. The host i am telnetting to is a unix server. >How can i "exit" this login prompt if the user keys in wrong password >in my script? Either do an explicit read_until() for the prompt and fail if it times out or use expect() to see whether you saw "Password:" or prompt. If you absolutely don't know what the prompt might be I suppose you could do another read_until("Password:") and if it times out then assume you got through. From petr at tpc.cz Thu Mar 9 04:42:55 2006 From: petr at tpc.cz (Petr Jakes) Date: 9 Mar 2006 01:42:55 -0800 Subject: accesibility of the namespace Message-ID: <1141897375.385047.258520@j52g2000cwj.googlegroups.com> In my code I have relatively wide dictionary definition (about 100 rows). I would like to put it in to the different file (module) because of the main code readability (say the name of the file will be "my_dictionary.py") In the dictionary I have strings formatted using % operator like: lcd={2:"Your credit= %3d" % (credit)} While I am trying to import my_dictionary in to the main code, I am getting: exception unhandled NameError name "credit" is not defined How can I organize my code so the "credit" variable will be "visible" in the "my_dictionary" namespace? Thanks Petr Jakes From sudharsh at gmail.com Wed Mar 29 09:29:14 2006 From: sudharsh at gmail.com (sudharsh at gmail.com) Date: 29 Mar 2006 06:29:14 -0800 Subject: Find similar images using python In-Reply-To: <442a95b5$1@nntp0.pdx.net> References: <1143637570.842988.44030@z34g2000cwc.googlegroups.com> <442a95b5$1@nntp0.pdx.net> Message-ID: <1143642554.075130.150990@e56g2000cwe.googlegroups.com> I dont get it..cant the matching take place efficiently with PIL, only that you need to have a condition i.e if the mismatch exceeds a certain threshold, they are not similar, http://gumuz.looze.net/wordpress/index.php/archives/2005/06/06/python-webcam-fun-motion-detection/ Check the above link, only diiference is that instead of files as in ur case, the code here compares two pixels of consecutive frames for changes.. Sudharshan S From kent at kentsjohnson.com Mon Mar 6 20:44:11 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 06 Mar 2006 20:44:11 -0500 Subject: Mixin class error In-Reply-To: References: <440cd84c_3@newspeer2.tds.net> Message-ID: <440ce0a6$1_3@newspeer2.tds.net> Ed Leafe wrote: > On Mar 6, 2006, at 8:08 PM, Kent Johnson wrote: >> One workaround might be to use delegation instead of subclassing... > > Yeah, but that would involve a lot more work at this point. The > mixin approach has been working quite well up until this problem. Automatic delegation is pretty simple, just define __getattr__() and __setattr__() to delegate to the wrapped class. For example http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52295 Kent From webraviteja at gmail.com Thu Mar 16 02:22:07 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 15 Mar 2006 23:22:07 -0800 Subject: Other languages for PVM In-Reply-To: <1142491840.639326.254640@p10g2000cwp.googlegroups.com> References: <1142491840.639326.254640@p10g2000cwp.googlegroups.com> Message-ID: <1142493727.778654.269570@z34g2000cwc.googlegroups.com> Yes! But not many. http://www.livelogix.net/logix/ Logix also allows you to create your own custom languages for Python's VM. But for some reason, there does not seem to be much interest in it's development. Odd, given that it has great potential. From jstroud at ucla.edu Tue Mar 7 15:37:15 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 07 Mar 2006 12:37:15 -0800 Subject: Peter Naur wins ACM Turing Award In-Reply-To: <1141762342.250962.228770@j33g2000cwa.googlegroups.com> References: <1141713321.760459.66010@j33g2000cwa.googlegroups.com> <18fPf.157$xM2.46142@news20.bellglobal.com> <1141762342.250962.228770@j33g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: > Colin J. Williams wrote: > > >>Without detracting from the last sentence, I disagree. >> >>Peter Naur's honour is long overdue. >> >>Colin W. > > > Sometimes it's hard for me to figure out about what somebody else > disagrees with me in particular when I agree with him. > > Is it possible that Peter Naur was forgotten when John Backus received > the Turing Award right in time in 1977? > > Kay > If you are going to publish, its important to choose a last name that starts with a letter at the front of the alphabet, lest you languish indefinitely in anonymity like Peter Naur. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From sjdevnull at yahoo.com Tue Mar 7 18:38:03 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 7 Mar 2006 15:38:03 -0800 Subject: Learning different languages In-Reply-To: References: Message-ID: <1141774680.015315.57790@j52g2000cwj.googlegroups.com> Rich wrote: > Anyway, my question is: what experience you people have with working > with different languages at the same time? At any given time, I'm doing a fair amount of Python and C work. I also do a lot of bash scripting for supporting frameworks. Beyond that I use a fair number of domain-specific languages depending on the problem at hand (SQL, XSL, etc). And from the shell I'm often doing one-offs in sed/awk, etc. > I'm more thinking about Python, PHP, C++, Perl, Euphoria, which are > languages I'm thinking of learning now. They look much more like each > other than basic and MC, at places some even share the exact same > syntax it seems, so your brain might get confused with what language > you're actually working with? It seems like it's not much of a problem in practice. I will occasionally find myself using wrong-languages constructs for things so simple that my brain is on cruise control (a simple for loop or conditional) but usually catch it before I'm even done typing the line. And for anything that requires any amount of thought it's just not an issue. Interestingly, I do some work on remote servers with minimal support infrastructure (bare vim w/o syntax highlighting, auto-indent, etc) and it doesn't seem to hurt much as far as "wrong language" goes. It's generally more language-independent features that those features help catch (unbalanced parens, typos, etc). > How is your experience with handling these paralell?. And what would > you recommend - take one (or perhaps two) at a time, and then continue > with the next? Or is it OK to go ahead with them all, at once? I would probably recommend _learning_ one language at a time until you're pretty comfortable with the basics. But learning a language (as opposed to the libraries, which take longer to get familiar with but are much less likely to be conflated) is a pretty fast process. From onurb at xiludom.gro Wed Mar 29 04:07:36 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 29 Mar 2006 11:07:36 +0200 Subject: tips for this exercise? In-Reply-To: References: Message-ID: <442a4e98$0$7724$636a55ce@news.free.fr> John Salerno wrote: > I'm working on another exercise now about generating random numbers for > the lottery. What I want to do is write a function that picks 5 random > numbers from 1-53 and returns them. Here's what I have so far: > > numbers = range(1, 54) > > def genNumbers(): > for x in range(5): > fiveNumbers = [] You rebind fiveNumbers on each iteration - so the results of the previous iteration are lost. > number = random.choice(numbers) > numbers.remove(number) ok, you already know the problem with this line > fiveNumbers = fiveNumbers.append(number) list.append() returns None. Guess what will be the value of fiveNumbers after this statement ? > return fiveNumbers And you exit the function at the first iteration. > Other than being sort of ugly, this also has the side effect of actually > editing the original list, This is not the only problem here !-) > which I don't want since I will want to > generate more than one set of numbers. > > Is there a better way to extract a certain number of items from a list > (so maybe I don't need the for loop)? Is a list even the right type to > use, since it gets edited in place? Perhaps a set? Your code is wrong, but still close to the simplest solution. Using random.choice() and removing used items from the list to choose from seems quite ok to me. Now shat you need to do is: 1/ create a new list to choose from each time the function is called 2/ create the results list *before* the loop 3/ return *after* the loop The simplest fix: def genNumbers(): choose_from = range(1, 54) results = [] for x in range(5): number = random.choice(choose_from) choose_from.remove(number) results.append(number) # end for return results -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sathyaish at gmail.com Mon Mar 20 11:02:27 2006 From: sathyaish at gmail.com (Sathyaish) Date: 20 Mar 2006 08:02:27 -0800 Subject: Chained Comparisons In-Reply-To: References: <1142835847.348629.177950@z34g2000cwc.googlegroups.com> Message-ID: <1142870547.355546.71100@u72g2000cwu.googlegroups.com> Thanks for the encouragement, Steve. I am learning Python out of earnest; I am intrigued by several languages such as Ruby, Python and Lisp. At work, I program VB6 (used to), VB.NET, C# and C over the Win32 platform. > that Sathyaish's time is more important than your time, of course. LOL. Certainly didn't mean that. :-) From danbrwn at gmail.com Mon Mar 27 10:38:28 2006 From: danbrwn at gmail.com (Dan) Date: 27 Mar 2006 07:38:28 -0800 Subject: COM server / COM client Message-ID: <1143473908.544188.52760@i40g2000cwc.googlegroups.com> Does the COM server created with python have to be compiled? I have the need to integrate database access but, I can not have any proprietary software. Meaning no compiled programs built by me. So, if python can do com clients and servers without compiling, Im good. But I don't know if that is possible. The ctypes example implies that it must be compiled using py2exe. I know the clients don't have to be compiled. What about the server? From mforbes at lns.mit.edu Thu Mar 2 22:24:48 2006 From: mforbes at lns.mit.edu (mforbes at lns.mit.edu) Date: Thu, 2 Mar 2006 19:24:48 -0800 Subject: how to overload sqrt in a module? In-Reply-To: <44079e05$1_3@newspeer2.tds.net> References: <44079e05$1_3@newspeer2.tds.net> Message-ID: >> I would like to write a module that provides some mathematical functions on >> top of those defined in math, cmath etc. but I would like to make it work >> with "any" type that overloads the math functions. >> >> Thus, I would like to write: >> >> module_f.py >> ---- >> def f(x): >> """ Compute sqrt of x """ >> return sqrt(x) >> >>>>> from math import * >>>>> import module_f >>>>> module_f.f(3) >> >> Traceback (most recent call last): >> File "", line 1, in ? >> File "module_f.py", line 2, in f >> return sqrt(x) >> NameError: global name 'sqrt' is not defined >> >> I understand why sqrt is not in scope, but my question is: what is the best >> way to do this? > > You need to import math in the module that uses it. Imports in one module > don't (in general) affect the variables available in another module. > > module_f.py > ---- > from math import sqrt # more explicit than from math import * > def f(x): > """ Compute sqrt of x """ > return sqrt(x) > > Kent I know, but the point is that I want to allow the user of the module to be able to specify which sqrt function should be used depending on the type of x. Importing math in the module would prevent the user from using f() with complex types (or dimensioned types for another example). That is why I suggested the ugly, but functional solution module_g.py ----------- def g(x,a_math): """Compute sqrt of x using a_math.sqrt) return a_math.sqrt(x) The user can at least specify to use cmath instead of math: >>> import cmath, module_g >>> module_g.g(8j,cmath) (2+2j) Michael. From tjreedy at udel.edu Sun Mar 19 00:38:54 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 19 Mar 2006 00:38:54 -0500 Subject: strange math? References: <1142745707.384085.42050@i39g2000cwa.googlegroups.com> Message-ID: >>>>f(01) > 43 >>>>f(02) > 44 >>>>f(010) > 50 >>>>42+010 > 50 Literal ints with lead 0 are interpreted as octal numbers (base 8) instead of decimal numbers (base 10). 01==1 either way, but 010 == 8. >>> 010 8 0x (zero eks) prefix indicate hexadecimal numbers: >>> 0xff 255 Terry Jan Reedy From sullivanz.pku at gmail.com Tue Mar 28 12:40:24 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 28 Mar 2006 09:40:24 -0800 Subject: No Cookie: how to implement session? Message-ID: <1143567624.164865.71730@v46g2000cwv.googlegroups.com> I do not want to use Cookies in my site since not all web browser support it well and sometimes people close cookie functioning for security reasons. I tried to add hidden field with a sessionID in every python CGI script generated web pages, so everytime my client POST a request, the server will retrieve the sessionID and decide if it is in the same session. However, since python cgi do not have a function for redirecting to a page, I use Location: url http head or javascript for redirecting.in this case, hidden field could not be used any more. Really wish python would have session management or equivalent in standard CGI module~~~~ From fredrik at pythonware.com Thu Mar 9 10:36:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 9 Mar 2006 16:36:40 +0100 Subject: Hashtables in pyhton ... References: Message-ID: Konrad M?hler wrote: > are there predefinded chances to use hashtables in python? How can I use > Hashtable in python? Or do I have to implement this on my own? is this what you want? http://docs.python.org/tut/node7.html#SECTION007500000000000000000 From golgote at gmail.com Sun Mar 12 02:25:20 2006 From: golgote at gmail.com (Bertrand Mansion) Date: Sun, 12 Mar 2006 08:25:20 +0100 Subject: Cheese Shop -> BSOL? In-Reply-To: References: Message-ID: <6a246d8e0603112325p251ebb3ep7f09c1e1d9446964@mail.gmail.com> On 3/12/06, Andrew Gwozdziewycz wrote: > > Look at the 'tadpoles' (i don't really think it's tadpoles really... > but i'll bite for now), > notice that it is a + sign, which we also always associate with life, > and health (red cross comes to mind). Python > is a healthy language. I can read it and write it without going blind > or crazy. The cross, the snake and the S shape are indeed very commonly associated with a medical universe. The current logo would be perfect for a drug company. > >Better eggs.python.org. Would support the spread of the new file > >format, too. > > eggs.python.org actually seems quite good to me. It'd be even cooler > if we could make EGGS an acronym for something. > How about 'Excellently Good Getting Solution' ? (joking). +1 for eggs.python.org ---- Bertrand From kent at kentsjohnson.com Sat Mar 18 23:15:25 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sat, 18 Mar 2006 23:15:25 -0500 Subject: Can I use a conditional in a variable declaration? In-Reply-To: <1142741039.554379.182170@g10g2000cwb.googlegroups.com> References: <1142741039.554379.182170@g10g2000cwb.googlegroups.com> Message-ID: <441cd5dc$1_2@newspeer2.tds.net> volcs0 at gmail.com wrote: > I want the equivalent of this: > > if a == "yes": > answer = "go ahead" > else: > answer = "stop" > > in this more compact form: > > > a = (if a == "yes": "go ahead": "stop") If the value for the 'true' case can never have a boolean value of False, you can use this form: a = (a == "yes") and "go ahead" or "stop" The short-circuit evaluation of 'and' and 'or' give the correct result. This will not work correctly because the 'and' will always evaluate to "" which is False so the last term will be evaluated and returned: a = (a == "yes") and "" or "stop" and IMO the extra syntax needed to fix it isn't worth the trouble; just spell out the if / else. Kent From tchur at optushome.com.au Sat Mar 11 15:59:45 2006 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 12 Mar 2006 07:59:45 +1100 Subject: Cheese Shop: some history for the new-comers In-Reply-To: References: <44126523$0$1016$afc38c87@news.optusnet.com.au> Message-ID: <44133A41.7030806@optushome.com.au> A.M. Kuchling wrote: > On Sat, 11 Mar 2006 16:50:26 +1100, > richard wrote: >> So I did what people always do in this situation, I asked Barry Warsaw to >> name. it. And he did, "Cheese Shop". I liked the name, so it was done. When >> the new pydotorg machines went live last year, so too did the name >> cheeseshop.python.org > > Given the endless whiny complaints about the name, I was just hoping that honour would be bestowed upon me for suggesting a brilliant alternative name, but I sense it is not to be...oh well (whistles tune to himself). > though, I think we > should just give up and go back to PyPI (pronounced 'Pippy'). Perusable Index of Packages for PYthon -> PIPPY (or PipPy if CamelCase is preferred, or pippy...). PyPi is doomed to be mispronounced pie-pie. Anyway, thanks to Richard Jones for all his work on PyPI/Cheese Shop, whining about the name notwithstanding. Tim C From onurb at xiludom.gro Wed Mar 22 04:53:49 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 22 Mar 2006 10:53:49 +0100 Subject: Per instance descriptors ? Message-ID: <44211ee8$0$7890$636a55ce@news.free.fr> Hi I'm currently playing with some (possibly weird...) code, and I'd have a use for per-instance descriptors, ie (dummy code): class DummyDescriptor(object): def __get__(self, obj, objtype=None): if obj is None: return self return getattr(obj, 'bar', 'no bar') class MyClass1(object): def __init__(self, bar=None): if bar is not None: self.bar = bar self.baaz = DummyDescriptor() mc1 = MyClass1(bar='back') mc1.baaz -> <__main__.DummyDescriptor object at 0x2aaaabc6c390> Which is of course what one would expect... Now I tried the following hack^Mworkaround: class MyClass2(MyClass1): def __getattribute__(self, key): v = MyClass1.__getattribute__(self, key) if hasattr(v, '__get__'): return v.__get__(self, self.__class__) return v And it *seems* to work just fine: mc2 = MyClass2(bar='foo') mc2.baaz -> 'foo' Now the question: is there any obvious (or non-obvious) drawback with this approach ? A bit of context: 1/ the real class is a decorator for controller functions in a mod_python application, and given previous experiences with mod_python, I'd prefer not mess with the class itself at runtime... still I'd like to abstract some gory details, and descriptors would be an obvious choice here. 2/ this is for production code, so robustness is more important than syntactic sugar - but having this syntactic sugar would be nice... Any hint ? TIA -- 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 Mon Mar 13 06:14:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Mar 2006 12:14:39 +0100 Subject: Anomalous behaviour when compiling regular expressions? References: <5959791F562E9E47B90254AECFD55B3B30D8A4@UKEXBE01.UK.CorpLAN.net> Message-ID: Harvey.Thomas at informa.com wrote: > >>> import re > >>> r = re.compile('(a|b*)+') > Traceback (most recent call last): > File "", 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 > > but > > >>> r = re.compile('(a|b*c*)+') > >>> r.match('def').group() > '' > > Why is there a difference in behaviour between the two cases. Surely the > two cases are equivalent to: > > >>> r = re.compile('(a|b)*') > >>> r.match('def').group() > '' equivalent? >>> re.match("(a|b*c*)", "abc").groups() ('a',) >>> re.match("(a|b)*", "abc").groups() ('b',) I have no time to sort out why your second example doesn't give the same error (that might be a bug in the RE compiler), but no, a repeated group with a min-length of 1 is not, in general, the same thing as a re- peated group with a min-length of zero. From steve at holdenweb.com Sun Mar 12 13:19:01 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Mar 2006 18:19:01 +0000 Subject: Cheese Shop: some history for the new-comers In-Reply-To: <44144E19.6070003@pollenation.net> References: <44126523$0$1016$afc38c87@news.optusnet.com.au> <44141D59.6050806@pollenation.net> <4414234F.7020605@pollenation.net> <44144E19.6070003@pollenation.net> Message-ID: Tim Parkin wrote: > Fredrik Lundh wrote: > >>Tim Parkin wrote: >>I surely hope you're not optimizing the site only for people who don't in- >>tend to leave the front page... >> > > > I sureley hope you can stop being facetious.. > And I surely hope we can all work together for the better representation of Python to *all* of its communities :-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From jess.austin at gmail.com Sat Mar 4 15:15:48 2006 From: jess.austin at gmail.com (jess.austin at gmail.com) Date: 4 Mar 2006 12:15:48 -0800 Subject: Easy immutability in python? References: <20060304115259.2e426ca8@samwise.anansi> Message-ID: <1141503348.781599.6050@p10g2000cwp.googlegroups.com> I guess we think a bit differently, and we think about different problems. When I hear, "immutable container", I think "tuple". When I hear, "my own class that is an immutable container", I think, "subclass tuple, and probably override __new__ because otherwise tuple would be good enough as is". I'm not sure how this relates to the clp thread that you cite. I didn't read the whole thing, but I didn't find it to be a flamewar so much as a typical clp contest of tedium, which failed to devolve into a flamewar simply due to the maturity of the interlocutors. To summarize: first post is a use case, second post is an implementation of that use case, and subsequent posts alternate between "that's not how I want to do it" and "please provide a more specific use case for which the provided implementation is not acceptable". good luck, Jess From tuvas21 at gmail.com Sun Mar 5 18:43:28 2006 From: tuvas21 at gmail.com (Tuvas) Date: 5 Mar 2006 15:43:28 -0800 Subject: Cryptographically random numbers In-Reply-To: References: <1141515788.580039.98240@v46g2000cwv.googlegroups.com> Message-ID: <1141602207.968477.256880@j33g2000cwa.googlegroups.com> Good idea about the max and min values. Yes, urandom is os.urandom. s2num('blah') will convert the phrase blah to ascii, and treat them as if they were a big function. Anyone else whose still interested, I found another small bug, but it was in the modular (Again). It won't do much, but... I did test out the RSA from end to end, found another small bug (I imputed the text luke, and it decrypted to ekul), but it works good now. Hopefully there's nothing left gaping, thanks for the help! From aleaxit at yahoo.com Fri Mar 10 10:46:08 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 10 Mar 2006 07:46:08 -0800 Subject: Python and C References: <1142001002.398147.199140@j52g2000cwj.googlegroups.com> Message-ID: <1hbz3xv.l0przi1mvgdo8N%aleaxit@yahoo.com> wrote: > I was a C Programmer for a while. Lately started to learn Python for > one small project at school. I joined a small company where they use > C++ for development. > > Can we use Python and C together ? I mean create some classes in Python > and some number crunching algorithms coded in C (for speed) and > integreate both of them. Sure! It's extremely common practice, known as "extending Python". > Could somebody just show a real small example or give pointers to the > same. Besides the Extending/Embedding and C API documents which are part of the standard set of Python docs, to which you've already been pointed in other responses, you can find tutorials on the net. A tiny one is at , with pointers to other materials. Also, examples can be found in the Demos directory of the Python source distribution -- even if you have a binary distro installed, get the source distro anyway, it's full of goodies and you can use much of Python itself as an example of Extending (the Modules and Objects directories of the source distro, in particular, are just such examples). C is the lowest, most fundamental level of extension, but there are many other alternatives -- SWIG to wrap existing libraries, Boost or SCXX or SIP to wrap specifically C++ with very different philosophies (template heavy, minimal, Qt-based), pyrex (a Python "dialect" plus C-like declarations to make it compilable to fast machine code), and others yet. Alex From __peter__ at web.de Fri Mar 31 01:50:13 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 31 Mar 2006 08:50:13 +0200 Subject: logging producing redundant entries References: Message-ID: Jed Parsons wrote: > I'm using the logging module for the first time. I'm using it from > within Zope Extensions. > > My problem is that, for every event logged, the logger is producing > multiple identical entries with the timestamp the same down to the > millisecond. > > Is this something I'm doing wrong? > > Log snippet: > > 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons > 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons > 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons > 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons > 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons > 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons > 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons > 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons > > I would like only one of the above lines in my log file; not all those > copies. > > I'm using this simple logging setup at the top of a zope Extension module: > > import logging > # basicConfig for python 2.3 > logging.basicConfig() > _logger = logging.getLogger("login") > _logger.setLevel(logging.DEBUG) > _handler = logging.FileHandler(LOG_ROOT, 'login.log')) > _formatter = logging.Formatter("%(asctime)s %(levelname)s: > %(message)s") > _handler.setFormatter(_formatter) > _logger.addHandler(_handler) > > So these are global to the module. The log lines above were produced by > what I expected would be a single call to _logger.info() in a function > in the module: > > _logger.info("Login: %s %s" % (firstname, lastname)) > > Can anyone explain what I'm doing wrong? Many thanks, Please cut and paste -- the FileHandler arguments are wrong and there is an extra ')'. As alex23 said, basicConfig() adds a handler, but that logs to stderr by default. You seem to be executing the code given above multiple times. You can verify that by prepending your snippet with f = open("metalog.txt", "a") f.write("configuring handler\n") f.close() If metalog.txt contains multiple lines after your program has terminated (you may have to shut down Zope -- don't know about that), a quick fix might be import logging if not logging.root.handlers: # your setup code Peter From johnjsal at NOSPAMgmail.com Wed Mar 1 00:36:21 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 01 Mar 2006 00:36:21 -0500 Subject: Use empty string for self In-Reply-To: <120a94q7qnhb97@corp.supernews.com> References: <1141170846.619246.163470@t39g2000cwt.googlegroups.com> <120a94q7qnhb97@corp.supernews.com> Message-ID: Grant Edwards wrote: >> A related thing I was wondering about was the use of 'self' in >> class methods as the first parameter. > > It's not a related thing, it's the same thing. Oh sorry. I thought the OP was asking about having to use self when qualifying attributes, or even if he was, I didn't realize it was the same principle as my question. And just now I was reading about new style classes, and it also seems like a bit of extra typing to have to subclass object, but I guess that isn't something that can be implied right now either. From rrr at ronadam.com Thu Mar 30 05:23:29 2006 From: rrr at ronadam.com (Ron Adam) Date: Thu, 30 Mar 2006 04:23:29 -0600 Subject: any() and all() on empty list? In-Reply-To: References: <1143630405.344694.269060@u72g2000cwu.googlegroups.com> Message-ID: <8nOWf.8849$Aa1.4205@dukeread05> Duncan Booth wrote: > Ron Adam wrote: > >> Where we are assembling widgets in a manufacturing plant. Where we don't >> want to go to the next step until *all* the sub parts are present. >> >> if all(part.status == 'present' for part in unit): >> do_release() >> >> Oops! Some empty bins showed up at the next assembly station. ;-) > > I don't see the problem. You only get an empty bin if there is some part > assembled from no sub-parts, in which case you wanted an empty bin. Hmmm... It wasn't a well though out example. I was thinking in terms of several processes working at the same time, and not communicating with each other. Ie.. a bin getter, a part inserter, a part checker, a bin mover. etc. But even then if all the parts get marked as 'present' even though they are aren't there, the bin could be released to the next station. And so that example is void. I'll try and think of a better one. Cheers, Ron From uval at rz.uni-karlsruhe.de Thu Mar 16 20:39:11 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Fri, 17 Mar 2006 02:39:11 +0100 Subject: My Generator Paradox! In-Reply-To: <1142554666.740989.303350@p10g2000cwp.googlegroups.com> References: <1142554666.740989.303350@p10g2000cwp.googlegroups.com> Message-ID: it's easy to explain class X: pass x=X() y=X() x and y are different instances one can put in x x.item = 1 y doesn't even have an attribute item for example similar with generators they are *different* objects of same kind generator >>> def fib(): ... a,b = 1,1 ... while True: ... a,b = b,a+b ... yield a,b ... >>> f1 = fib() >>> f2 = fib() >>> f1 >>> f2 # different addresses >>> f1 is f2 False >>> f1.next() (1, 2) >>> f1.next() (2, 3) >>> f1.next() (3, 5) >>> >>> >>> f2.next() (1, 2) >>> it's only natural that each objects starts it's own fibonaci serie hth, Daniel From mkluwe at gmail.com Wed Mar 8 15:05:08 2006 From: mkluwe at gmail.com (Matthias Kluwe) Date: 8 Mar 2006 12:05:08 -0800 Subject: [wxpython] StaticBoxSizer problems Message-ID: <1141848308.410869.90390@z34g2000cwc.googlegroups.com> Hi! I'd like to place several StaticBoxes in a frame, but I can't get it right. Consider the following code: import wx app = wx.PySimpleApp() frame = wx.Frame(parent=None, title="Test") box = wx.BoxSizer(wx.VERTICAL) frame.SetSizer(box) upper_box = wx.StaticBox(parent=frame, label="Upper Box") box.Add(item=upper_box, flag=wx.GROW) upper_sizer = wx.StaticBoxSizer(upper_box) upper_sizer.Add(wx.Button(parent=frame, label="Button")) frame.Show() app.MainLoop() This should show a frame containing a StaticBox which contains a button, but: The button is not placed within the StaticBox. Hmm. Additionally: wx.StaticBoxSizer.__init__.__doc__ says that a StaticBoxSizer is created by __init__(self, StaticBox box, int orient=HORIZONTAL). But if I change the line upper_sizer = wx.StaticBoxSizer(upper_box) to upper_sizer = wx.StaticBoxSizer(StaticBox=upper_box) I get the error: TypeError: new_StaticBoxSizer() takes at least 1 argument (0 given). What am I missing? Regards, Matthias From felipe.lessa at gmail.com Fri Mar 3 04:32:19 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 03 Mar 2006 06:32:19 -0300 Subject: How much does Python optimize? In-Reply-To: References: Message-ID: <1141378339.3967.0.camel@kenshin> Em Sex, 2006-03-03 ?s 10:26 +0100, Blackbird escreveu: > However, range(10) in the command interpreter obviously returns a list. Is > this list optimized away in the code above, or is it actually constructed > internally? (With, say, CPython in one of the recent versions.) It's constructed. That's why you should use xrange. -- "Quem excele em empregar a for?a militar subjulga os ex?rcitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destr?i os estados dos outros povos sem lutas prolongadas. Deve lutar sob o C?u com o prop?sito primordial da 'preserva??o'. Desse modo suas armas n?o se embotar?o, e os ganhos poder?o ser preservados. Essa ? a estrat?gia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" From support at 2extremestudios.com Tue Mar 28 13:31:23 2006 From: support at 2extremestudios.com (support at 2extremestudios.com) Date: 28 Mar 2006 10:31:23 -0800 Subject: web Message-ID: <1143570683.864865.246560@e56g2000cwe.googlegroups.com> Hello, 2ExtremeStudios.com would like to offer you a great deal on a brand new website for your business. We invite you to visit www.2ExtremeStudios.com, we offer business information site design and e-store integration, as well as other services. Thanks for your time, Daniel N. Phone. 1.416.834.1592 e-mail. support at 2extremestudios.com url. http://2ExtremeStudios.com From caleb.hattingh at gmail.com Tue Mar 28 15:48:32 2006 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 28 Mar 2006 12:48:32 -0800 Subject: Simple py script to calc folder sizes In-Reply-To: References: <1142983179.378155.92340@v46g2000cwv.googlegroups.com> Message-ID: <1143578912.180456.252770@v46g2000cwv.googlegroups.com> Thanks John I will use your code :) 30% improvement is not insignificant, and that's what I was looking for. I find the log function a little harder to read, but I guess that is a limitation of me, not your code. Caleb From fredrik at pythonware.com Sat Mar 11 04:59:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 11 Mar 2006 10:59:19 +0100 Subject: Using len() References: <1142065856.986016.181530@j33g2000cwa.googlegroups.com><1142067948.542553.162530@i39g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote: > I don't know why input() is the equivalent of eval(raw_input(prompt)), but > it is. Presumably Guido thought it was a good idea at the time. possibly inspired by ABC's "READ" and "READ RAW" commands: http://homepages.cwi.nl/~steven/abc/qr.html From fumanchu at amor.org Sun Mar 12 19:07:52 2006 From: fumanchu at amor.org (fumanchu) Date: 12 Mar 2006 16:07:52 -0800 Subject: Help Create Good Data Model References: <1142107183.358685.266440@i39g2000cwa.googlegroups.com> <1142115988.067193.239570@i39g2000cwa.googlegroups.com> <1142123948.052804.5450@i40g2000cwc.googlegroups.com> <1142197521.068087.72040@v46g2000cwv.googlegroups.com> <1142201751.544046.75150@v46g2000cwv.googlegroups.com> <1142203630.415688.198860@i39g2000cwa.googlegroups.com> Message-ID: <1142208472.285149.192200@j33g2000cwa.googlegroups.com> If you used a Queue, it wouldn't be the container itself; rather, it would be a gatekeeper between the container and consumer code. A minimal example of user-side code would be: class Request: def __init__(self, op, data): self.op = op self.data = data self.reply = None req = Request('get', key) data_q.put(req, block=True) while req.reply is None: time.sleep(0.1) do_something_with(req.reply) The container-side code would be: while True: request = data_q.get(block=True) request.reply = handle(request) That can be improved with queue timeouts on both sides, but it shows the basic idea. Robert Brewer System Architect Amor Ministries fumanchu at amor.org From cginboston at hotmail.com Wed Mar 1 09:43:33 2006 From: cginboston at hotmail.com (Chance Ginger) Date: Wed, 01 Mar 2006 14:43:33 GMT Subject: Writing an applilcation that can easily adapt to any language Message-ID: I am rather new at Python so I want to get it right. What I am doing is writing a rather large application with plenty of places that strings will be used. Most of the strings involve statements of one kind or another. I would like to make it easy for the support people to port the application from one language to another, German, Spanish, etc. Rather than make them search all over for the strings to replace is there a library that I can use to make this all easier? I keep thinking of resources in Java, as an example. Is there anything like it in Python? Peace, Chance. From frank at chagford.com Mon Mar 20 08:23:28 2006 From: frank at chagford.com (Frank Millman) Date: 20 Mar 2006 05:23:28 -0800 Subject: Pycrypto - active ?? In-Reply-To: <1142856119.461122.293150@i40g2000cwc.googlegroups.com> References: <1142804398.710230.117640@j33g2000cwa.googlegroups.com> <1142807299.141313.306980@i40g2000cwc.googlegroups.com> <1142841321.980154.320340@u72g2000cwu.googlegroups.com> <7xslpdl7yg.fsf@ruckus.brouhaha.com> <1142856119.461122.293150@i40g2000cwc.googlegroups.com> Message-ID: <1142861008.662593.172900@t31g2000cwb.googlegroups.com> dirvine wrote: > Thanks Paul > > I will check this out. Perhaps theres a case for pycrypto to be > revamped and perhaps a new python cryptographic page to be created > mentioning all these projects. I have foudn it a bit difficult to find > info on this area. Mny thanks for this though. Just as a BTW - I have recently installed TLSLite on linux and on MSW, and it seems to work fine The docs say that if you have any of m2crypto, cryptlib, pycrypto, or GMPY installed, it will be used for fast cryptographic operations. I installed M2Crypto on linux, and indeed, after the initial handshake, there is hardly any noticeable slowdown. However, I have not found an MSW binary for Python 2.4 for any of the above packages. TLSLite works ok by itself, but it is noticeably slower when transferring large amounts of data. Frank Millman From bpeng at rice.edu Sat Mar 4 18:30:27 2006 From: bpeng at rice.edu (Bo Peng) Date: Sat, 04 Mar 2006 17:30:27 -0600 Subject: Suggestions for documentation generation? In-Reply-To: <1141240014.302680.78850@z34g2000cwc.googlegroups.com> References: <1141240014.302680.78850@z34g2000cwc.googlegroups.com> Message-ID: kpd wrote: > Hello, > > I have written a C++ library that I've then wrapped with Pyrex. > Any suggestions to the best-in-class tool to create documentation for > the libraries? > > I would love to document things in one spot (could be the code) and > generate html and PDF from there. > > Doxygen (www.doxygen.org) looks to be about the best so far. > > I was facing the same problem and took the following approach: 1. write c++ code with doxygen-complaint comments 2. generate XML comments using doxygen 3. parse XML and generate Python docstring 4. insert the docstring into SWIG interface file I can send you the parser but I do not know if pyrex support python docstring. Bo From walterbyrd at iname.com Tue Mar 28 13:30:11 2006 From: walterbyrd at iname.com (walterbyrd) Date: 28 Mar 2006 10:30:11 -0800 Subject: Looking for a language/framework In-Reply-To: <4429603c$0$7916$636a55ce@news.free.fr> References: <1143559444.045808.38790@u72g2000cwu.googlegroups.com> <4429603c$0$7916$636a55ce@news.free.fr> Message-ID: <1143570611.300606.241400@e56g2000cwe.googlegroups.com> > You can bet it'll be plain old cgi - possibly with an outdated Pyton version. I think you are right. In practical terms, what does that mean? Will I not be able to use modules? Will I not be able to use frameworks? > Which frameworks have you looked at ? django, turbogears, cheetah, cherrypy, . . . By "looked at" I mean I read up on them, a little. I have not tried any of them. From neurogasm at gmail.com Wed Mar 22 21:53:51 2006 From: neurogasm at gmail.com (Kevin F) Date: Wed, 22 Mar 2006 21:53:51 -0500 Subject: newbie question Message-ID: what does it mean when there are [0] or [1] after a variable? e.g. print 'Message %s\n%s\n' % (num, data[0][1]) From deets at nospam.web.de Mon Mar 13 06:27:01 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 13 Mar 2006 12:27:01 +0100 Subject: Environmental Variables References: <1142246053.485766.41280@i39g2000cwa.googlegroups.com> <1142247707.381011.154410@i39g2000cwa.googlegroups.com> Message-ID: <47l38jFg13c3U1@uni-berlin.de> > was what I got. I checked the at DOS prompt (cmd) for PYTHONSTARTUP, > and I got an 'unrecognized program/command/batch file' interrupt. > > What's the deal with environmental variables? Are they specific to an > interpreter session? That shouldn't be. Yes they are - and yes, it should be that way. A process inherits the environment of its parent. It can set its own environment, and if it forks children, these will see that. But there is no way for a process to alter the environment of its parent, let alone some arbitrary other process. This is an OS-limitation (or feature) - so if you absolutely have to convince somebody that it is bad, try Redmond :) DIez From jeffrey at fro.man Sat Mar 25 11:20:28 2006 From: jeffrey at fro.man (Jeffrey Froman) Date: Sat, 25 Mar 2006 08:20:28 -0800 Subject: MySQLDB - return strange type of variable References: <1j5qvk5e0u2o8.254nllrv5t1n$.dlg@40tude.net> Message-ID: <122are51drdgk88@corp.supernews.com> Grzegorz Smith wrote: > Hi all. I'm trying get data from text field in MySQl 5.0 with my National > characters. Data are stored in utf8 encodings. Here is the script: > import MySQLdb, MySQLdb.cursors > conn = MySQLdb.connect(host='localhost', user='root', passwd='123456', > db='profile_locale') > c = conn.cursor(MySQLdb.cursors.DictCursor) > c.execute("SET CHARACTER SET utf8") > c.execute("SELECT string_value FROM lang_pl_pl WHERE id=8") > row = c.fetchone() > print row > and i get: > {'string_value': array('c', 'Zmie\xc5\x84 has\xc5\x82o')} > where it come array type? Recent versions of MySQL/MySQLdb return "binary strings" as Python array objects, rather than bytestrings (I think the change was around version 4.2 of MySQL.) Details on array objects are here: http://www.python.org/doc/lib/module-array > How can i get value 'Zmie\xc5\x84 has\xc5\x82o' ?? array('c', 'Zmie\xc5\x84 has\xc5\x82o').tostring() > If I do c.fetchone -shouldn't i get type tuple? If you use the default MySQLdb cursor object you will get a tuple. Using the DictCursor as you are returns a dictionary instead. Jeffrey From tjreedy at udel.edu Mon Mar 13 13:13:56 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 13 Mar 2006 13:13:56 -0500 Subject: Is this possible in Python? References: <1142238871.199749.243470@p10g2000cwp.googlegroups.com> Message-ID: wrote in message news:1142238871.199749.243470 at p10g2000cwp.googlegroups.com... > Hi > > I wonder if Python is capable of the following: define a function which > returns its argument. > I mean: > def magic_function(arg): > ...... some magic code ... > > that behaves the following way: > > assert magic_function(3+4)=="3+4" > assert magic_function([i for i in range(10)])=="i for i in range(10)]" The arguments to Python functions are Python objects. In order to return the argument as a string, you must pass it as a string. >>> def magic(s): return s, eval(s) >>> magic('3+4') ('3+4', 7) >>> magic('[i**2 for i in [1,2,3]]') ('[i**2 for i in [1,2,3]]', [1, 4, 9]) Terry Jan Reedy From steven.bethard at gmail.com Thu Mar 9 22:53:27 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 09 Mar 2006 20:53:27 -0700 Subject: Why property works only for objects? In-Reply-To: References: Message-ID: Michal Kwiatkowski wrote: > Code below shows that property() works only if you use it within a class. Yes, descriptors are only applied at the class level (that is, only class objects call the __get__ methods). > Is there any method of making descriptors on per-object basis? I'm still not convinced that you actually want to, but you can write your own descriptor to dispatch to the instance object (instead of the type): >>> class InstanceProperty(object): ... def __init__(self, func_name): ... self.func_name = func_name ... def __get__(self, obj, type=None): ... if obj is None: ... return self ... return getattr(obj, self.func_name)(obj) ... >>> class C(object): ... x = InstanceProperty('_x') ... >>> c = C() >>> c.x Traceback (most recent call last): File "", line 1, in ? File "", line 7, in __get__ AttributeError: 'C' object has no attribute '_x' >>> def getx(self): ... return 42 ... >>> c._x = getx >>> c.x 42 STeVe From mathweijzen at home.nl Tue Mar 28 09:29:12 2006 From: mathweijzen at home.nl (Math) Date: Tue, 28 Mar 2006 16:29:12 +0200 Subject: 1.090516455488E9 / 1000000.000 ??? Message-ID: <003d01c65273$fcb2c9d0$0502a8c0@AS4L> Hello, I got a simple and probably stupid newby question.. When I compute: 1.090516455488E9 / 1000000 the result is 1090516455.49 Should be 1090516455.488 I know something with float and //... Anybody? How do I get correct number? From steve at holdenweb.com Sun Mar 19 16:32:15 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 19 Mar 2006 21:32:15 +0000 Subject: Relative paths in mod_python In-Reply-To: References: Message-ID: Ivo van der Sangen wrote: > I was wondering if I could use relative paths in a mod_python script. At > the moment I am defining a constant string > "/path/to/dir/where/script/resides". The problem with this is that when > I move the script including files I use to get metadata I have to change > this variable. The same problem occurs when I distribute the script; the > person using it will first have to modify it, which is not what I want. Is > it possible that a mod_python script has as current working directory > the directory where the script resides? At the moment os.getcwd() > returns '/'. import os req.write(os.path.abspath(__file__)) seems to give you the absolute path to the module you are executing. You can use the other os.path primitives to extract the directory from that and use it to locate the associated data files. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From bdesth.quelquechose at free.quelquepart.fr Fri Mar 10 21:52:04 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 11 Mar 2006 03:52:04 +0100 Subject: Why property works only for objects? In-Reply-To: References: Message-ID: <44120f8c$0$21102$626a54ce@news.free.fr> Michal Kwiatkowski a ?crit : > Steven Bethard napisa?(a): > >>>Is there any method of making descriptors on per-object basis? >> >>I'm still not convinced that you actually want to, but you can write >>your own descriptor to dispatch to the instance object (instead of the >>type): > > > Ok, this works for attributes I know a name of at class definition. What > about other situations? I could possibly want to have different sets of > attributes for instances of a class. Then you want a different class for each different set of attributes. > Is it still possible to do? I don't > also like current solution, as it wraps things around, creating another > attribute ('_x') in the process. Aren't there any cleaner solutions? > > The problem is I have an instance of a given class (say BaseClass) and I > want it to implement some attribute accesses as method calls. I'm not a > creator of this object, so changing definition of BaseClass or > subclassing it is not an option. What you want is delegation. Which is pretty easy with Python, look at __getattr__ and __setattr__. > Code below doesn't work, but shows my > intention: > > # obj is instance of BaseClass > def get_x(self): > # ... > def set_x(self, value): > # ... > obj.x = property(get_x, set_x) class ObjWrapper(object): def __init__(self, obj): self.obj = obj # special case x def _get_x(self): return self.obj.x def _set_x(self, value): self.obj.x = value x = property(fget=_get_x, fset=_set_x) # default lookup, directly delegate to obj def __getattr__(self, name): return getattr(self.obj, name) def __setattr__(self, name, value): # this one is a bit more tricky # and I don't remember it right now, # but it's in the fine manual anyway obj = ObjWrapper(obj) obj.x # calls ObjWrapper._get_x() > Changing __setattr__/__getattr__ of an object also doesn't work for the > same reason: dictionary lookup is made only in class attributes, > ommiting object attributes. It's confusing, because writting obj.x and > obj.__getattribute__('x') gives a different results. There also seems > not to be any clear way to define methods for objects. Something like: > > class C(object): > pass > > def method(self): > return self.x > > c = c.x > c.method = method > c.method() # => AttributeError import types c.method = types.MethodType(method, c, c.__class__) > So another question arise. Is it possible to make function a method (so > it will receive calling object as first argument)? Yeps, just wrap it in a Method object (cf above) From singletoned at gmail.com Wed Mar 29 11:59:30 2006 From: singletoned at gmail.com (Ed Singleton) Date: Wed, 29 Mar 2006 17:59:30 +0100 Subject: Doc suggestions (was: Why "class exceptions" are not deprecated?) In-Reply-To: References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com> <1143574346.354680.136060@i39g2000cwa.googlegroups.com> <34bb7f5b0603290047o21b9a1b7k64cdd206f604fc10@mail.gmail.com> <34bb7f5b0603290752p48a1b818x4570d189153cbcdc@mail.gmail.com> <34bb7f5b0603290753w42d463d8gd975523a5ae7d7ab@mail.gmail.com> Message-ID: <34bb7f5b0603290859k7738e253v2c9aec2dae93aff5@mail.gmail.com> On 29/03/06, Fredrik Lundh wrote: > Ed Singleton wrote: > > > > alright, I got bored and uploaded a copy of the current Python tutorial to > > > > > > http://pytut.infogami.com > > > > Damn. You beat me to it by an hour. > > > > http://singletoned.infogami.com/_special/index > > oops. sorry for that. Not at all. I'm quite proud that it was only an hour. > > > I had a nightmare with character encodings (mainly because I'm > > > terrible with them). I have a script written that does it all for me, > > > but it keeps choking on characters. I just tried randomly converting > > > things to Unicode at various points for over an hour until it worked. > > sounds weird. iirc, there were only one page that contained non-ascii > characters, and the latest html2text.py script had no problems dealing > with that one. node4 and node5 caused problems for me. I'm still struggling a bit with character encodings so that probably caused most of my problems. > > Also, your looks better than mine. > > did you look at it before or after I added the new stylesheet? ;-) Before. Now it looks gorgeous. > > Did you write a script to do the table of contents too? > > nope; I did that all by hand. I plan to write some scripts to get contents > *out* of infogami, though, but that'll have to wait for some other day. > > anyway, do you want to keep your version, or should we "standardize" on > the pytut version ? and are there any willing community contributors out > there? Standardise on yours obviously, though I might keep mine around to keep playing with the script. It's a bit clumsy at the moment, but I can see there's some potential there for having a general script to rip content out of sites and put it in a wiki (if only for the rest of the python docs, should this project succeed). I'd also be interested in seeing how you did it as it would be the first time I could directly compare what I did to how an expert does it. I'd suggest adding some sort of guidance page so that people know roughly what's expected. IE can they just add questions and comments into the text, hoping that someone more knowledgeable will sort it out (or delete it). Ed From http Thu Mar 23 14:51:25 2006 From: http (Paul Rubin) Date: 23 Mar 2006 11:51:25 -0800 Subject: Remove integer from float number References: <1143142664.507941.130240@g10g2000cwb.googlegroups.com> <4422FAA9.50506@websafe.com> <1143143275.684150.299200@i39g2000cwa.googlegroups.com> Message-ID: <7xk6alvt1e.fsf@ruckus.brouhaha.com> "Derek Basch" writes: > Ahh yes you have to put parenthases around the string formatting to > remove the integer using indexes. Thanks, that's just what I needed! I think it's better to remove leading zeros explicitly: ('%.3x' % x).lstrip('0') From g.horvath at gmx.at Tue Mar 14 02:12:05 2006 From: g.horvath at gmx.at (Gregor Horvath) Date: Tue, 14 Mar 2006 08:12:05 +0100 Subject: Basic python help In-Reply-To: References: Message-ID: <2955b$44166cc5$506c2949$25559@news.chello.at> Kevin Feng schrieb: > More information about this error may be available in the server error log. > > > > Any suggestions? Much thanks. > What does the error log of the webserver say? -- Greg From kbk at shore.net Thu Mar 2 00:28:24 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Thu, 2 Mar 2006 00:28:24 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200603020528.k225SO9n008883@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 382 open ( -3) / 3079 closed (+12) / 3461 total ( +9) Bugs : 880 open (+16) / 5624 closed ( +3) / 6504 total (+19) RFE : 211 open ( +0) / 201 closed ( +1) / 412 total ( +1) New / Reopened Patches ______________________ PEP 357 --- adding nb_index (2006-02-21) http://python.org/sf/1436368 opened by Travis Oliphant Test of PEP 357 (2006-02-21) CLOSED http://python.org/sf/1436377 opened by Travis Oliphant Size of time_t changed to 64 bits in MSVC++ 2005 CRT (2006-02-23) http://python.org/sf/1437769 opened by Atul Varma dict.getdefault() implementation (2006-02-24) CLOSED http://python.org/sf/1438113 opened by Barry A. Warsaw PEP 0328 (relative import) implementation (2006-02-24) CLOSED http://python.org/sf/1438387 opened by Thomas Wouters Patch for bug 1438185: os.renames deletes junction points (2006-02-26) http://python.org/sf/1439312 opened by Grant Olson issue syntax warning for with becoming a keyword (2006-02-27) CLOSED http://python.org/sf/1439917 opened by Neal Norwitz Add col information to parse & ast nodes (2006-02-28) CLOSED http://python.org/sf/1440601 opened by John Ehresman asdl generation changes (2006-02-28) CLOSED http://python.org/sf/1440620 opened by John Ehresman Stop help() crashing with incorrect privileges (2006-03-01) http://python.org/sf/1440660 opened by splitscreen Inconsistency in os' function naming (2006-03-01) http://python.org/sf/1440928 opened by Frederik 'Freso' S. Olesen Updated Demo\parser\unpack.py (2006-03-02) http://python.org/sf/1441452 opened by John Ehresman Patches Closed ______________ Implement PEP 357 for real (2006-02-11) http://python.org/sf/1429591 deleted by teoliphant Test of PEP 357 (2006-02-21) http://python.org/sf/1436377 deleted by teoliphant add collections.defaultdict (2006-02-17) http://python.org/sf/1433928 closed by gvanrossum dict.getdefault() implementation (2006-02-24) http://python.org/sf/1438113 closed by gvanrossum PEP 0328 (relative import) implementation (2006-02-24) http://python.org/sf/1438387 closed by nnorwitz PyThreadState_Delete doesnt' clean autoTLSkey (2006-01-23) http://python.org/sf/1413181 closed by tim_one issue syntax warning for with becoming a keyword (2006-02-27) http://python.org/sf/1439917 closed by nnorwitz PEP 343 with statement (2006-02-21) http://python.org/sf/1435715 closed by gvanrossum Inline Lambda patch (2006-02-18) http://python.org/sf/1434008 closed by loewis More easily extensible logging module (2006-01-22) http://python.org/sf/1412054 closed by vsajip Add col information to parse & ast nodes (2006-02-28) http://python.org/sf/1440601 closed by loewis asdl generation changes (2006-02-28) http://python.org/sf/1440620 closed by jpe new-style exceptions (2005-01-18) http://python.org/sf/1104669 closed by bcannon unknown locale: lt_LT (patch) (2005-02-08) http://python.org/sf/1118341 closed by nerijus New / Reopened Bugs ___________________ urllib has trouble with Windows filenames (2006-02-21) http://python.org/sf/1436428 opened by Donovan Eastman length of unicode string changes print behaviour (2006-02-22) http://python.org/sf/1436532 opened by James urllib.py overwrite HTTPError code with 200 (2005-04-06) http://python.org/sf/1178141 reopened by gbrandl Problem parsing cmdline parameter quoted with a trailing \ (2006-02-22) CLOSED http://python.org/sf/1436900 opened by Wai Yip Tung "continue" in .pdbrc has no effect (2006-02-22) http://python.org/sf/1437051 opened by Coolheads Consulting can't send files via ftp on my MacOS X 10.3.9 (2006-02-23) http://python.org/sf/1437614 opened by Li Quid robotparser crashes if robots.txt contains non-ASCII (2006-02-23) http://python.org/sf/1437699 opened by osvenskan Problems w/ expat 1.95.7 vs. Python 2.4 (2006-02-23) http://python.org/sf/1437785 opened by Skip Montanaro os.renames() crashes NTFS junctions (2006-02-24) http://python.org/sf/1438185 opened by Daniel Rohlfing shutil.move raises OSError when copystat fails (2006-02-25) http://python.org/sf/1438480 opened by Joe Wreschnig modules search in help() crashes on insufficient file perms (2006-02-25) http://python.org/sf/1438537 opened by A. Coder test -e is not portable (Solaris 2.7) (2006-02-27) http://python.org/sf/1439538 opened by H??vard Tveite file to store pickled object should be opened in binary mode (2006-02-27) http://python.org/sf/1439659 opened by Raghuram Devarakonda email.Generator is not idempotent (2006-02-28) http://python.org/sf/1440472 opened by WonderClown UnicodeWriter: "utf-8" hardcoded instead of self.encoding (2006-03-01) http://python.org/sf/1440831 opened by Rodrigo Daunoravicius No simple example for pickle (2006-03-01) http://python.org/sf/1441072 opened by Kent Johnson set update method description is incorrect (2006-03-01) http://python.org/sf/1441264 opened by Richard King compiler module loses docstrings (2006-03-02) http://python.org/sf/1441397 opened by Michael Hudson svn head compiler fails to spot extended slicing (2006-03-02) http://python.org/sf/1441408 opened by Michael Hudson Bugs Closed ___________ Problem parsing cmdline parameter quoted with a trailing \ (2006-02-22) http://python.org/sf/1436900 closed by gbrandl Reading from a killed shell script with popen* under linux (2005-05-03) http://python.org/sf/1194328 closed by boukthor exception cannot be new-style class (2002-02-17) http://python.org/sf/518846 closed by bcannon Standard exceptions are hostile to Unicode (2004-08-20) http://python.org/sf/1012952 closed by bcannon New / Reopened RFE __________________ yday in datetime module (2006-02-21) http://python.org/sf/1436346 opened by Michael Toews RFE Closed __________ Extend pre-allocated integers to cover [0, 255] (2006-02-21) http://python.org/sf/1436243 closed by gbrandl From marc.wyburn at googlemail.com Fri Mar 31 02:01:21 2006 From: marc.wyburn at googlemail.com (marc.wyburn at googlemail.com) Date: 30 Mar 2006 23:01:21 -0800 Subject: C++ and Python Message-ID: <1143788481.360935.20560@u72g2000cwu.googlegroups.com> I've been learning to write VST plugins in C++ and would like to switch back to Python. The first step of writing the plugin is to import the C++ header files from the Steinberg SDK. How can I do this in Python. I've tried looking at SWIG but didn't really understand what it was trying to do. Should I be using SWIG to create Python versions of the classes and then go from there or does it create glue code to talk to the classes. From tuvas21 at gmail.com Sat Mar 4 12:57:28 2006 From: tuvas21 at gmail.com (Tuvas) Date: 4 Mar 2006 09:57:28 -0800 Subject: Random Prime Generator/Modular Arithmetic In-Reply-To: <1141493449.312867.225160@j33g2000cwa.googlegroups.com> References: <1141487100.450422.306010@v46g2000cwv.googlegroups.com> <1hbo45c.6kg75cbrxcaiN%aleaxit@yahoo.com> <1141493449.312867.225160@j33g2000cwa.googlegroups.com> Message-ID: <1141495047.945510.234410@v46g2000cwv.googlegroups.com> Okay, the bug in my code has been fixed, it should work alot better now... I thought I had tested the power function, but I appearently wasn't even close... But now it works just fine. I guess you are right, I will have to work on a better system to be cryptologically secure. But, at least I have a start. Thanks for the help! From fakeaddress at nowhere.org Sat Mar 11 03:50:54 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 11 Mar 2006 08:50:54 GMT Subject: Using len() In-Reply-To: <1142065856.986016.181530@j33g2000cwa.googlegroups.com> References: <1142065856.986016.181530@j33g2000cwa.googlegroups.com> Message-ID: ctilly at gmail.com wrote: [...] > But I would like to change it to be something like.... > > while yourguess != mynum: > > tries = tries + 1 > yourguess = input("Your guess? ") > > if len(yourguess)==0: > continue [...] > But this throws the following error and I have no idea why. Please > enlighten. > > My error ==> len() of unsized object The innocent sounding function "input()" actually invokes the perilous "eval()". Read about it at: http://docs.python.org/lib/built-in-funcs.html Try "rawinput()" instead. -- --Bryan From mcassiano at manord.com Fri Mar 3 10:14:27 2006 From: mcassiano at manord.com (Cassiano, Marco) Date: Fri, 3 Mar 2006 16:14:27 +0100 Subject: Incorrect Decimal-Float behaviour in comparison tests Message-ID: I have difficulties with a weird Python 2.4.2 behaviour in comparing Decimal to Floats. For Example : >>> from decimal import Decimal >>> a=Decimal('3.7') >>> b=6.3 >>> if a > b :print a,b,'a is greater than b - NOT TRUE!!!!' ... else: print a,b,'b is greater than a - CORRECT' ... 3.7 6.3 a is greater than b - NOT TRUE!!!! Have you ever encountered this behaviour ? It seems a bug to me... Do you konw if there is any patch available for this? Thank you very much Marco Cassiano Manifatture del Nord srl unipersonale Gruppo MaxMara viale Regina Elena 13-15 42100 Reggio Emilia RE ITALY Sede operativa: via Mazzacurati 6 42100 Reggio Emilia RE ITALY Tel. +39 0522 358215 Fax +39 0522 268715 email : mcassiano at manord.com From johnpote at blueyonder.co.uk Fri Mar 3 19:09:02 2006 From: johnpote at blueyonder.co.uk (John Pote) Date: Sat, 04 Mar 2006 00:09:02 GMT Subject: sockets, where can I find documentation? References: Message-ID: Thanks everyone for such a quick response. Brilliant! John Pote "John Pote" wrote in message news:lXVNf.104670$YJ4.55822 at fe2.news.blueyonder.co.uk... > Hi all, > > I want to use python on a server to access incoming TCP port accesses. So > I need to use the socket interface which is new to me. To quote the Py > Library Reference "7.2 socket -- Low-level networking interface":- > > For an introduction to socket programming (in C), see the following > papers: An Introductory 4.3BSD Interprocess Communication Tutorial, by > Stuart Sechrest and An Advanced 4.3BSD Interprocess Communication > Tutorial, by Samuel J. Leffler et al, both in the Unix Programmer's > Manual, Supplementary Documents 1 (sections PS1:7 and PS1:8). The > platform-specific reference material for the various socket-related system > calls are also a valuable source of information on the details of socket > semantics. For Unix, refer to the manual pages; for Windows, see the > WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers may > want to refer to RFC 2553 titled Basic Socket Interface Extensions for > IPv6. > > Where can I get the various papers mentioned in the manual? And as I like > books sitting on the shelf can someone recommend a book on sockets. > > many thanks, > > John Pote > From tjreedy at udel.edu Fri Mar 10 13:12:06 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 10 Mar 2006 13:12:06 -0500 Subject: time series calculation in list comprehension? References: <1142012049.892323.103060@v46g2000cwv.googlegroups.com> Message-ID: "falcon" wrote in message news:1142012049.892323.103060 at v46g2000cwv.googlegroups.com... > Is there a way I can do time series calculation, such as a moving > average in list comprehension syntax? I'm new to python but it looks > like list comprehension's 'head' can only work at a value at a time. I > also tried using the reduce function and passed in my list and another > function which calculates a moving average outside the list comp. ... > but I'm not clear how to do it. Any ideas? Thanks. Write explicit for loops, possibly with nested if conditionals, that do exactly what you want. The functional expressions are abbreviations for certain patterns of induction. Except as an educational exercise, I do not think it worthwhile to go through contortions to force fit a problem to a pattern it does not really fit. Terry Jan Reedy From larry.bates at websafe.com Wed Mar 1 16:14:04 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 01 Mar 2006 15:14:04 -0600 Subject: Stopping Windows Service In-Reply-To: <1141245687.785561.24450@j33g2000cwa.googlegroups.com> References: <1141245687.785561.24450@j33g2000cwa.googlegroups.com> Message-ID: <44060E9C.7050607@websafe.com> D wrote: > I have a simple file server utility that I wish to configure as a > Windows service - using the examples of the Python Win32 book, I > configured a class for the service, along with the main class functions > __init__, SvcStop, and SvcDoRun (which contains my server code). After > registering the service, I am able to start it with no problems. > However, it never stops correctly (net stop returns "service could not > be stopped") and service is left in a Stopping state. My gut tells me > there's something additional I need to include in the SvcDoRun function > in order to have it shutdown gracefully, but I'm not sure what. Also, > if that is the case, where should I place the statements within the > function (i.e. right after the listen() statement?)? Thanks as > always.. > > Doug > Stopping is done by having SvcStop set the event flag so that the next time through your loop in SvcDoRun you see that the stop has been issued and exit your while loop. Here is some skeleton code that I stripped from a working service. Hope it helps. Note: I copied most of this from Mark Hammond and Andy Robinson's excellent book Python Programming on Win32 book. -Larry Bates import win32serviceutil import win32service import win32event import win32evtlogutil class testService(win32serviceutil.ServiceFramework): def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) #--------------------------------------------------------------------- # Create an event which we will use to wait on. # The "service stop" request will set this event. #--------------------------------------------------------------------- self.hWaitStop=win32event.CreateEvent(None, 0, 0, None) return def SvcStop(self): #--------------------------------------------------------------------- # Before we do anything, tell SCM we are starting the stop process. #--------------------------------------------------------------------- self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) #--------------------------------------------------------------------- # And set my event #--------------------------------------------------------------------- win32event.SetEvent(self.hWaitStop) return def SvcDoRun(self): import servicemanager #--------------------------------------------------------------------- # Make entry in the event log that this service started #--------------------------------------------------------------------- servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) #--------------------------------------------------------------------- # Wait 10000 milliseconds (10 seconds) #--------------------------------------------------------------------- self.timeout=10000 #----------------------------------------------------------------- # Wait for service stop signal, if I timeout, loop again #----------------------------------------------------------------- rc=win32event.WaitForSingleObject(self.hWaitStop, self.timeout) # # Check to see if self.hWaitStop happened # if rc == win32event.WAIT_OBJECT_0: # # Stop signal encountered # break #--End while-- #--------------------------------------------------------------------- # Log stopped message to EventLog #--------------------------------------------------------------------- servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, '')) return From dananrg at yahoo.com Tue Mar 7 16:38:08 2006 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: 7 Mar 2006 13:38:08 -0800 Subject: Problem with dbi, odbc module and Oracle 9.2 - suffixed "L" with number data type References: <1141293671.315768.186560@i39g2000cwa.googlegroups.com> Message-ID: <1141767488.919422.327450@e56g2000cwe.googlegroups.com> Thanks Andrew. > I've been bugging ESRI about upgrading, and I'm sure others have too. The beta of ArcGIS Desktop 9.2 ships with Python 2.4, so I imagine the release of ArcGIS Desktop 9.2 this summer will also ship with Python 2.4. I've read threads recently on the geoprocessing / scripting support.esri.com of people using Python 2.4 successfully for geoprocessing but I've not tried to install it yet. Check out: http://forums.esri.com/Thread.asp?c=93&f=1729&t=157014 And also this support article: http://support.esri.com/index.cfm?fa=knowledgebase.techarticles.articleShow&d=26872 Let me know if you have any luck with this. Dana From bignose+hates-spam at benfinney.id.au Wed Mar 1 22:00:09 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 02 Mar 2006 14:00:09 +1100 Subject: PEP 354: Enumerations in Python References: <87accdplbj.fsf@rose.polar.local> <1141019214.153904.115220@j33g2000cwa.googlegroups.com> <877j7gz53k.fsf@rose.polar.local> <7xd5h8jnk1.fsf@ruckus.brouhaha.com> <87hd6j3s51.fsf@rose.polar.local> <7xhd6ilxk2.fsf@ruckus.brouhaha.com> Message-ID: <87k6bdsg91.fsf@rose.polar.local> Paul Rubin writes: > I don't know about this. It makes athlon64_instructions a > completely separate enum from pentium_instructions. It could be > that athlon64_instructions.add should be the same as > pentium_instructions.add . If you want the members of two distinct collections to have a meaningful relationship, you don't want enumerations. The basic promise of the specified enumeration interface is that every member of an enumeration is a unique value. -- \ "A society that will trade a little liberty for a little order | `\ will lose both, and deserve neither." -- Thomas Jefferson, in | _o__) a letter to Madison | Ben Finney From larry.bates at websafe.com Fri Mar 10 16:43:04 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 10 Mar 2006 15:43:04 -0600 Subject: MS Access db (mdb): viewing table attributes In-Reply-To: <1142013201.717227.282050@i39g2000cwa.googlegroups.com> References: <1142013201.717227.282050@i39g2000cwa.googlegroups.com> Message-ID: gau.tai at gmail.com wrote: > I have an Access 2003 database, protected by a workgroup, that I am > trying to view through python. Currently, I'm attempting dao with the > win32 package, and I'm able to view all of the table names, but I don't > know how to view the attributes of the tables. > > My code: > > import win32com.client > from pprint import pprint > > #sample code to list all tables in the selected database > daoEngine = win32com.client.Dispatch('DAO.DBEngine.36') > dtbs = daoEngine.OpenDatabase('database_file.mdb') > for table in dtbs.TableDefs: > if table.Name[:4] <> "MSys" and table.Name[:4] <> "~TMP": > pprint(table.Name.encode('utf-8')) > #the above works, but below does not: > for col in table.Fields: > pprint(col.Name, Col.Type, Col.Size) > > I am getting that len(Fields) = 0, and I know the database tables are > all full of columns (and data). Is there also some resource that > defines all the properties of TableDefs? I wasn't able to find a > python reference for this. > > Thank You, > Gau > Not quite sure about DAO but when I use ODBC I get the fieldnames by doing (stripped from working program): crsr.execute(SQL_query) fieldinfo=crsr.description fieldnames=["%s" % i[0].lower() for i in fieldinfo] Hope this helps. -Larry Bates From tdelaney at avaya.com Wed Mar 8 17:53:11 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 9 Mar 2006 09:53:11 +1100 Subject: Simple questions on use of objects (probably faq) Message-ID: <2773CAC687FD5F4689F526998C7E4E5F07435B@au3010avexu1.global.avaya.com> Max M wrote: > decorated = [(obj.x, obj) for obj in objects] > max_decorated = max(decorated) > max_obj = max_decorated[-1] Python 2.5 will make this even easier - max() and min() aquire a `key` keyword parameter much like list.sort()/sorted(). max_obj = max(objects, key=operator.attrgetter('x')) Also, using your DSU version, you should (nearly) always include the object index in the tuple so you don't break ties by comparing the actual objects i.e. decorated = [(obj.x, i, obj) for (i, obj) in enumerate(objects)] max_decorated = max(decorated) max_obj = max_decorated[-1] Note that this will always return the *last* entry with maximum obj.x as the max - to return the first one found, use (obj.x, -i, obj). Tim Delaney From sybrenUSE at YOURthirdtower.com.imagination Fri Mar 10 10:04:29 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 10 Mar 2006 16:04:29 +0100 Subject: why use special config formats? References: <1142002082.976945.261900@e56g2000cwe.googlegroups.com> Message-ID: tomerfiliba at gmail.com enlightened us with: > i came to this conclusion a long time ago: YOU DON'T NEED CONFIG > FILES FOR PYTHON. why re-invent stuff and parse text by yourself, > why the interpreter can do it for you? Because you generally don't want to give the configuration file writer full control over the Python virtual machine. > for the most common case, static configuration, you just have a > human-edited config file holding key-and-value pairs. so just add to > your package a file called config.py, and import it. Which only works if there is only one configuration file per installation of your package, and is writable by the users that need to configure it. For example, per-user database connection parameters should be in $HOME/.programrc on UNIX systems. A program's preference settings should be stored in a user-writable file to, preferably in the user's homedir. 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.petrazzo at TOGLIunipex.it Tue Mar 28 11:27:46 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Tue, 28 Mar 2006 18:27:46 +0200 Subject: String split In-Reply-To: References: <442945dd$0$29097$5fc30a8@news.tiscali.it> Message-ID: <442963ff$0$29106$5fc30a8@news.tiscali.it> Peter Otten wrote: > The documentation for Python 2.4 has a better explanation. > <-cut-> > Quoted after http://docs.python.org/lib/string-methods.html#l2h-202. > > Peter Thanks, I haven't see it. Just a question about that "different algorithm", because it force the developer to do other work for make the "split" result more "logically compatible": S = "" # this can become from an external source like config parser for s n S.split(): do the work... # don't go inside that isn't "compatible", so python split it into two different methods the string, with: for s n S.split(','): do the work... # run one time into this Michele From nospamformeSVP at gmail.com Mon Mar 27 08:59:02 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Mon, 27 Mar 2006 08:59:02 -0500 Subject: MVC in Python for web app dev In-Reply-To: <1143348852.233308.89320@g10g2000cwb.googlegroups.com> References: <1143348852.233308.89320@g10g2000cwb.googlegroups.com> Message-ID: m.wanstall at gmail.com wrote: > I'm aware that Pylons is trying to > compete with Rails in the near future but I'm just not clear on how > directly they are trying to compete...will Pylons have the same > generation functions and other time saving goodies that RoR has or am I > barking up the wrong tree? > Thanks for the reference to Pylon: http://pylonshq.com/ I had not heard of it before and it looks promising. Have you asked your questions ('the same generation functions and other time saving goodies') of the Pylon folks? Don. From wmmeyer at gmail.com Fri Mar 3 07:15:27 2006 From: wmmeyer at gmail.com (William Meyer) Date: Fri, 3 Mar 2006 12:15:27 +0000 (UTC) Subject: object's list index Message-ID: hi, I need to get the index of an object in a list. I know that no two objects in the list are the same, but objects might evaluate as equal. for example list = [obj1, obj2, obj3, obj4, obj5] for object in list: objectIndex = list.index(object) print objectIndex prints 0, 1, 2, 3, 2 instead of 0, 1, 2, 3, 4 because obj3 == obj5. I could loop through the list a second time comparing id()'s for object in list: objectIndex = 0 for i in list: if id(object) == id(i): break objectIndex += 1 print objectIndex but that seems like a real ugly pain. Somewhere, someplace python is keeping track of the current index in list, does anyone know how to access it? Or have any other suggestions? From danmcleran at yahoo.com Thu Mar 9 17:36:14 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 9 Mar 2006 14:36:14 -0800 Subject: creating an executable? In-Reply-To: References: Message-ID: <1141943773.958642.187860@z34g2000cwc.googlegroups.com> >Can I make an executable with just the standard distribution, or do I >need a separate module? Check out py2exe: http://www.py2exe.org/ From johnjsal at NOSPAMgmail.com Tue Mar 7 11:54:29 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 07 Mar 2006 16:54:29 GMT Subject: inserting into a list In-Reply-To: <475s0sFe4g15U1@uni-berlin.de> References: <475qs4Fdp9mhU1@uni-berlin.de> <475s0sFe4g15U1@uni-berlin.de> Message-ID: <9ViPf.1742$No6.40328@news.tufts.edu> Diez B. Roggisch wrote: > John Salerno wrote: > >> Diez B. Roggisch wrote: >> >>> Why don't you just _try_ that? It would have been way faster than to ask >>> questions you can easily answer yourself. >> I did try it, but I was still hoping for an explanation, which I've also >> gotten from you guys, some in nicer terms than others. > > You got an explanation to your first question from me. > > But you obviously _didn't_ try your second one. Which would be a no-brainer > as Warby's reply shows, and given that you already knew how to insert a > single element list I consider it being not so nice of _you_ not to do so, > but instead post before you tried. > > Diez Actually, I did try the second one too, but I'm not trying to get into a fight here, so let's just forget it. I appreciate the fact that you responded at all, and with answers to my questions. From arne at citde.net Thu Mar 23 10:46:41 2006 From: arne at citde.net (Arne Ludwig) Date: 23 Mar 2006 07:46:41 -0800 Subject: removing file by inode References: <1143090399.430131.224390@t31g2000cwb.googlegroups.com> <1225egub5k1kv3b@corp.supernews.com> Message-ID: <1143128801.255443.44910@v46g2000cwv.googlegroups.com> Good answer. :) I seriously doubt it is possible except for the trivial solution: def remove_a_file(inode): os.system ("find / -inum %d | xargs rm -f" % (inode)) PS. Don't blame me if this function destroys your hard disk. I wrote it off the top of my head. From jjl at pobox.com Fri Mar 24 17:13:06 2006 From: jjl at pobox.com (John J. Lee) Date: 24 Mar 2006 22:13:06 +0000 Subject: COM Client / Server creation? References: <1143060785.381056.208660@g10g2000cwb.googlegroups.com> <1143061924.070461.72060@t31g2000cwb.googlegroups.com> <87ek0urn3v.fsf@pobox.com> Message-ID: <87lkuzwky5.fsf@pobox.com> jjl at pobox.com (John J. Lee) writes: [...] > Not covered in the book, and particularly useful for implementing > native clients and servers is ctypes / comtypes (but still not stable; > also, I've only personally used it for writing a client, and a very > simple one at that): > > http://starship.python.net/crew/theller/ctypes/com.html Just to clarify this: ctypes IS stable, and in fact will be part of Python 2.5 (first alpha to be released in a week or so). comtypes is the "work-in-progress" (though it has been quite useable, at least for the simple stuff I did, for some time now). It's all quite elegant, too. John From vincent at visualtrans.de Sun Mar 19 16:41:24 2006 From: vincent at visualtrans.de (Vincent Wehren) Date: Sun, 19 Mar 2006 21:41:24 -0000 Subject: How to check if a directory is exist in python? References: <1142803465.164833.38160@j33g2000cwa.googlegroups.com> Message-ID: "Vincent Wehren" wrote in message news:dvkj3a$9vp$1 at news4.tilbu1.nb.home.nl... | wrote in message | news:1142803465.164833.38160 at j33g2000cwa.googlegroups.com... ||I check the documentation here, but it does not say how to check if a || directory is exist in python? || http://docs.python.org/lib/os-file-dir.html | | Look at the exist or isdir methods of the os.path module Ofcourse I mean "exists"... | (http://docs.python.org/lib/module-os.path.html} | || || And why mkdir fails if the directory already exists? | | If you prefer a "more friendly" approach you may wanna take a look at Trent | Mick's _mkdir which is located at | http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82465 || | | Regards, | Vincent Wehren | || Thank you. || | | From remi at cherrypy.org Thu Mar 9 10:07:06 2006 From: remi at cherrypy.org (remi at cherrypy.org) Date: 9 Mar 2006 07:07:06 -0800 Subject: ANN: CherryPy-2.2.0-rc1 released Message-ID: <1141916826.545884.24830@e56g2000cwe.googlegroups.com> Hello everyone, I'm happy to announce that the first release candidate for CherryPy-2.2.0 is now available. This release includes various bugfixes, a new benchmarking tool and improved WSGI support. Check out this great post from Christian Wyglendowski to see how you can run multiple WSGI-CherryPy apps using other tools like wsgutils or Paste (or do the opposite: run a PyBloxsom or MoinMoin WSGI app within CherryPy): http://blog.dowski.com/2006/03/08/cherrypy-and-wsgi-can-play-nice/ Christian has also put together a great screencast showing how to run CherryPy and interact with it directly from the prompt: http://blog.dowski.com/2006/03/05/cherrypy-and-the-interactive-interpreter/ *************** About CherryPy: CherryPy is a pythonic, lightweight and straightforward (no dependencies) web development framework. Here is a sample Hello, World in CherryPy: # import cherrypy # class HelloWorld: # @cherrypy.expose # def index(self): # yield "" # yield "Hello world!" # yield "" # cherrypy.root = HelloWorld() # cherrypy.server.start() Details and downloads for the 2.2.0-rc1 release are available from the CherryPy website: http://www.cherrypy.org Remi. From srikar2097 at gmail.com Tue Mar 7 11:30:10 2006 From: srikar2097 at gmail.com (sri2097) Date: 7 Mar 2006 08:30:10 -0800 Subject: Attaching files in windows using Python. Message-ID: <1141749010.184737.155850@p10g2000cwp.googlegroups.com> Hi all, I have to select a particular file (using the 'Browse') button in Windows. After this I need to populate the 'Open Dialogue Box' with the path of the file I need (I have the entier path of the file I need). Then I need to select the 'Open' Button. Only after this the file I want is attached. Any idea as to how this can be done using 'Win32 API's. While looking for the proper answer to this I found that 'Mark Hammond's' Python for Windows documentation is not detail enough. Any help in this regard would be much appreciated. From tedlandis at gmail.com Wed Mar 8 09:29:49 2006 From: tedlandis at gmail.com (Ted) Date: 8 Mar 2006 06:29:49 -0800 Subject: New python.org website In-Reply-To: <440ea467$0$38682$edfadb0f@dread12.news.tele.dk> References: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> <1141757893.030386.123090@i40g2000cwc.googlegroups.com> <440ea467$0$38682$edfadb0f@dread12.news.tele.dk> Message-ID: <1141828189.686141.216580@v46g2000cwv.googlegroups.com> Hear hear! I like it. It's not perfect but is much better than the old one in all ways. A huge improvement. Thanks to the website team. From steven.bethard at gmail.com Sun Mar 26 12:29:29 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 26 Mar 2006 10:29:29 -0700 Subject: pondering about the essence of types in python In-Reply-To: <1143374045.375304.313990@t31g2000cwb.googlegroups.com> References: <1143318547.286867.9940@u72g2000cwu.googlegroups.com> <1143374045.375304.313990@t31g2000cwb.googlegroups.com> Message-ID: gangesmaster wrote: > i dont think it's possible, to create proxy classes, but even if i did, > calling remote methods with a `self` that is not an instance of the > remote class would blow up. I don't understand you here. Why can't you just do something like: >>> class RemoteClass(object): ... def __init__(self, name): ... self.name = name ... def __repr__(self): ... return '%s(name=%s)' % (type(self).__name__, self.name) ... >>> rc = RemoteClass('foo') >>> rc RemoteClass(name=foo) >>> class ProxyClass(object): ... def __init__(self, name): ... self.remote = RemoteClass(name) ... def __repr__(self): ... return repr(self.remote) ... >>> pc = ProxyClass('foo') >>> pc RemoteClass(name=foo) Note that when I call methods on the remote class, I don't pass them an instance of the proxy class -- I pass them an instance of the appropriate, RemoteClass type. Of course my code is simplified because I'm not actually doing something remote, but assuming things get, say, pickled and unpickled appropriately, I'm not sure I understand why the above won't work. Could you give some more details? STeVe From kp8 at mac.com Tue Mar 14 19:36:16 2006 From: kp8 at mac.com (kpp9c) Date: 14 Mar 2006 16:36:16 -0800 Subject: markov query In-Reply-To: References: <1142309974.440477.192600@u72g2000cwu.googlegroups.com> Message-ID: <1142378132.911751.324180@i40g2000cwc.googlegroups.com> >Yes, a system which does this has to build a Markov >chain from a data set and then traverse it. >>Any program that actually uses Markov chains to generate >> new text based on existing input as you've described Hi. That isn't really what i have described. If i did i could use exsisting algorithms. What you describe is exactly what i don't want in this particular case. I am actually not wanting it to build a chain from some input that it analyzes. There is no input. If you see, i am trying to define a table that tells it how to proceed forward from scratch as a stochastic process. cheers, -kp-- From larry.bates at websafe.com Tue Mar 21 09:12:11 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 21 Mar 2006 08:12:11 -0600 Subject: Convert (sorted) list of dics to nested list ? In-Reply-To: <1142942266.400839.40840@t31g2000cwb.googlegroups.com> References: <1142942266.400839.40840@t31g2000cwb.googlegroups.com> Message-ID: <442009BB.60904@websafe.com> shearichard at gmail.com wrote: > Hi - I want to take something like ... > > lstIn = [] > lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 10, 'LEA_AUTOID': 1000}) > lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2000}) > lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2001}) > lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2003}) > lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3000}) > lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3001}) > lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3002}) > lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3003}) > lstIn.append({'COM_AUTOID': 2, 'PRG_AUTOID': 110, 'LEA_AUTOID': 4000}) > > > ... and produce something like ... > > sampleOut = > [[1,[10,1000]],[1,[11,[2000,2001,2003]]],[1,[12,[3000,3001,3002,3003]]],[2,[110,4000]] > > > Well I've now been around the block a few times with this one and I'm > still frowning !! In the process my code has become uglier and uglier - > I'm sure there must be quite an elegant way of dealing with it - could > anyone give me a push in the right direction ? > > Just to provide some motivation here - I should just say that this is > cut down test case - the real problem involves creating a Javascript > structure which in turn defines a three level menu. > > The resulting JS will be something like this, I think you can see how > the nested loops get into it.: > > var MENU_ITEMS = [ > { pos:'relative', leveloff:[b,a], itemoff:[d,c], size:[e,f], ... }, > { ...Item 1... }, > { ...Item 2... , > sub:[ > { ...level format... }, > { ...Item 1... }, > { ...Item 2... }, > { ...Item 3... , > sub:[ > { ...level format... }, > { ...Item 1... }, > { ...Item 2... }, > { ...Item 3... }, > { ...Item 4... } > ] > }, > { ...Item 4... }, > ] > }, > { ...Item 3... } > ]; > > Interested to hear of any smart/elegant ideas. > > thanks > > Richard. > Might not be 'elegant', but at least it works. -Larry lstIn = [] lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 10, 'LEA_AUTOID': 1000}) lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2000}) lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2001}) lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2003}) lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3000}) lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3001}) lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3002}) lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3003}) lstIn.append({'COM_AUTOID': 2, 'PRG_AUTOID': 110, 'LEA_AUTOID': 4000}) c="COM_AUTOID" p="PRG_AUTOID" l="LEA_AUTOID" lastc=None lastp=None sampleOut=[] for entry in lstIn: C=entry[c] P=entry[p] L=entry[l] if C != lastc or P != lastp: sampleOut.append([C,[P,L]]) else: sampleOut[-1:][0][1].append(L) lastc=C lastp=P print "sampleOut=", sampleOut From jdhunter at ace.bsd.uchicago.edu Wed Mar 15 12:17:53 2006 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 15 Mar 2006 11:17:53 -0600 Subject: FIR filtering References: <1142428703.224948.317700@u72g2000cwu.googlegroups.com> <1142431475.577039.286470@e56g2000cwe.googlegroups.com> <1142437453.065363.309720@i40g2000cwc.googlegroups.com> Message-ID: <87pskny6da.fsf@peds-pc311.bsd.uchicago.edu> >>>>> "Terry" == Terry Reedy writes: Terry> "LabWINC" wrote in message Terry> news:1142437453.065363.309720 at i40g2000cwc.googlegroups.com... >> If i type help scipy.filter it give me an error >> >> help scipy.filter File "", line 1 help scipy.filter ^ >> SyntaxError: invalid syntax Terry> The respondant left out parens. At interactive prompt: Terry> help(scipy.filter) or, in general help(someobject) Sorry, ipython user here -- http://ipython.scipy.org ipython supports autoparens.... JDH From rdh at new.rr.com Wed Mar 22 12:17:37 2006 From: rdh at new.rr.com (DataSmash) Date: 22 Mar 2006 09:17:37 -0800 Subject: import random module References: <1143046086.771003.43180@g10g2000cwb.googlegroups.com> <1143046848.154484.124700@j33g2000cwa.googlegroups.com> Message-ID: <1143047857.148396.118100@i39g2000cwa.googlegroups.com> Much Thanks! I deleted the random.pyc and renamed the script and everything is good! R.D. From ahcheriet at gmail.com Fri Mar 24 11:42:43 2006 From: ahcheriet at gmail.com (PythonStudent) Date: 24 Mar 2006 08:42:43 -0800 Subject: What's The Best Editor for python Message-ID: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> Hi, Can one of you say to me what's the best editor for editing the python programs ( for linux or windows ), and if you can send it to me to the adresse Ahcheriet at gmail.com Thanks From skip at pobox.com Tue Mar 21 13:25:34 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 21 Mar 2006 12:25:34 -0600 Subject: Can XML-RPC performance be improved? In-Reply-To: References: <1142962694.368445.43780@t31g2000cwb.googlegroups.com> Message-ID: <17440.17694.240743.306940@montanaro.dyndns.org> Steve> I suppose there *was* a good reason for using XML-RPC in the Steve> first place? I don't know about the OP, but in my case it was a drop-dead simple cross-language RPC protocol. At one point Mojam's XML-RPC server talked to clients written in Python, Perl and Objective-C (via a Java bridge, no less). Skip From onurb at xiludom.gro Thu Mar 30 09:22:08 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 30 Mar 2006 16:22:08 +0200 Subject: Non-GUI source code browser with file system tree view In-Reply-To: <442BDDED.6090702@sschwarzer.net> References: <442BDDED.6090702@sschwarzer.net> Message-ID: <442be9d1$0$19022$626a54ce@news.free.fr> Stefan Schwarzer wrote: > Hello, > > from time to time I want to inspect the source code of projects > on remote computers.(*) I've googled for one or two hours but > didn't find anything helpful. :-/ I'm looking for something like > IDLE's path browser - i. e. a tree view and file view > side-by-side - but with the following differences: > > - doesn't need an X connection to the remote computer where the > sources are > > - must also work with other programming languages (ideally with > syntax highlighting) > > - consequently, the tree view will not be based on a module > search path but on a file system directory > > Ideally, but not necessesarily, this browser should be written in > Python. If possible, it should be open source software. It _must_ > run on GNU/Linux and, if possible, on Mac OS X (a local X server > is ok if the mentioned browser is a curses-based program). > (Another approach might be a small web application server in the > spirit of "pydoc -p " which could connect to a local port > forwarded with ssh.) > > Does anyone know of a source code browser which meets the > requirements listed above or links that could help me? Many > thanks in advance. :-) emacs + emacs code browser. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From http Fri Mar 3 14:51:04 2006 From: http (Paul Rubin) Date: 03 Mar 2006 11:51:04 -0800 Subject: forcing exceptions References: Message-ID: <7xd5h3pas7.fsf@ruckus.brouhaha.com> Nikola Skoric writes: > Is there a way to tell the interpreter to display exceptions, even those > which were captured with except? Normally you wouldn't do that unless you were trying to debug the interpreter itself. It uses caught exceptions for all sorts of things that you probably don't want displayed. I think even ordinary loop termination may be implemented using exceptions. From fredrik at pythonware.com Thu Mar 23 08:36:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 23 Mar 2006 14:36:07 +0100 Subject: Simple but fundamental: How to import a jython class? References: <1143118315.105008.130510@z34g2000cwc.googlegroups.com> Message-ID: aziz.hammadi at gmail.com wrote: >I wrote a jython class bus I can not use it in another jython script > :-( > Example: > ---------------------- X.py---------------------- > class X: > def hello(): > print "Hello" > > > ---------------------- Y.py---------------------- > import X > x = X() > x.hello() > > I get TypeError: call of non function (module 'X') > Both files are in the same directory. after you've done "import X", the name X refers to the namespace of the module X.py, not the class (or any other object) in that module. to access the class, use dot notation: x = X.X() From buzzard at urubu.freeserve.co.uk Fri Mar 17 20:18:33 2006 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 18 Mar 2006 01:18:33 +0000 Subject: style guideline for naming variables? In-Reply-To: References: Message-ID: <441b5ef3.0@entanet> John Salerno wrote: > After reading the PEP, I'm still not quite sure if there is a > recommended (or widely preferred) method of naming variables. Here are > the relevant bits: > >> Global Variable Names >> >> (Let's hope that these variables are meant for use inside one >> module >> only.) The conventions are about the same as those for functions. >> >> Modules that are designed for use via "from M import *" should >> use the >> __all__ mechanism to prevent exporting globals, or use the the >> older >> convention of prefixing such globals with an underscore (which >> you might >> want to do to indicate these globals are "module non-public"). >> >> Function Names >> >> Function names should be lowercase, with words separated by >> underscores >> as necessary to improve readability. >> >> mixedCase is allowed only in contexts where that's already the >> prevailing style (e.g. threading.py), to retain backwards >> compatibility. > >> > >> Method Names and Instance Variables >> >> Use the function naming rules: lowercase with words separated by >> underscores as necessary to improve readability. >> >> Use one leading underscore only for non-public methods and instance >> variables. >> >> To avoid name clashes with subclasses, use two leading >> underscores to >> invoke Python's name mangling rules. >> >> Python mangles these names with the class name: if class Foo has an >> attribute named __a, it cannot be accessed by Foo.__a. (An >> insistent >> user could still gain access by calling Foo._Foo__a.) >> Generally, double >> leading underscores should be used only to avoid name conflicts >> with >> attributes in classes designed to be subclassed. >> >> Note: there is some controversy about the use of __names (see >> below). > > > It refers to instance variables, which I assume includes all variables > that aren't global, and the suggestion is to follow function > conventions, which would be this: > > some_function > > But this seems awkward to me. someFunction seems nicer, but it is > specifically mentioned not to do this for new code. > > So I'm just curious how other people handle the multiword situation. > Underscores, or Pascal case? SomeClass someFunction some_variable FWIW Duncan From fumanchu at amor.org Sat Mar 11 19:39:08 2006 From: fumanchu at amor.org (fumanchu) Date: 11 Mar 2006 16:39:08 -0800 Subject: Help Create Good Data Model References: <1142107183.358685.266440@i39g2000cwa.googlegroups.com> <1142115988.067193.239570@i39g2000cwa.googlegroups.com> Message-ID: <1142123948.052804.5450@i40g2000cwc.googlegroups.com> I didn't say that right. As long as you are using deepcopy (or any operation which might iterate over the keys or values in self.data), your setter methods need that mutex, *and* it should probably be a threading.Lock, not an RLock, just in case that iteration ends up mutating the dict somehow. You can "get away with" no mutexes only if *all* operations are atomic, meaning you'd have to at the least iterate over *copies* of the dict's keys. Otherwise, you need the mutex in your setters as well as your getters. That turns into a performance problem quickly, which is why there's so much literature out there on alternatives (mostly written by those designing databases). Once you hit the performance issues, you can try multiple dicts to simulate page locking, or cooperating locks to implement one-writer/multiple-readers, or other techniques. Dejavu uses a separate sandbox for each thread and lets the back end (usually a well-written database) handle the concurrency issues. There's a CachingProxy backend in dejavu/storage/__init__.py which has full locks as your app does. Of course, even atomic operations don't guarantee that overlapping threads do what you expect. If one thread sets self.data['a'] = 1 and another sets self.data = {}, the order of their operation may or may not be important to you. Robert Brewer System Architect Amor Ministries fumanchu at amor.org From peter at engcorp.com Mon Mar 20 21:45:18 2006 From: peter at engcorp.com (Peter Hansen) Date: Mon, 20 Mar 2006 21:45:18 -0500 Subject: Do anyone already have code to copy nested files to a flat directory? In-Reply-To: <1142906723.452980.258790@t31g2000cwb.googlegroups.com> References: <1142903578.911713.291400@u72g2000cwu.googlegroups.com> <1142906723.452980.258790@t31g2000cwb.googlegroups.com> Message-ID: Podi wrote: > OK, please don't bother. Here is my wheel :-) > > import os > import shutil > > def CopyFlat(source, target): > count = 0 > for root, dirs, files in os.walk(source): > for file in files: > count += 1 > name = root + '\\' + file A small improvement to the reinvented wheel: use os.sep instead of "\\", for portability. Better yet, use os.path.join() and avoid the manual joining of path parts. -Peter From no-spam at no-spam-no-spam.com Sat Mar 11 06:19:49 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 11 Mar 2006 12:19:49 +0100 Subject: "RuntimeError: dictionary changed size during iteration" ; Good atomic copy operations? Message-ID: In very rare cases a program crashes (hard to reproduce) : * several threads work on an object tree with dict's etc. in it. Items are added, deleted, iteration over .keys() ... ). The threads are "good" in such terms, that this core data structure is changed only by atomic operations, so that the data structure is always consistent regarding the application. Only the change-operations on the dicts and lists itself seem to cause problems on a Python level .. * one thread periodically pickle-dumps the tree to a file: >>> cPickle.dump(obj, f) "RuntimeError: dictionary changed size during iteration" is raised by .dump ( or a similar "..list changed ..." ) What can I do about this to get a stable pickle-dump without risiking execution error or even worse - errors in the pickled file ? Is a copy.deepcopy ( -> "cPickle.dump(copy.deepcopy(obj),f)" ) an atomic opertion with a guarantee to not fail? Or can I only retry several times in case of RuntimeError? (which would apears to me as odd gambling; retry how often?) Robert PS: Zope dumps thread exposed data structes regularly. How does the ZODB in Zope handle dict/list changes during its pickling operations? --- Python 2.4.1 (#2, May 5 2005, 11:32:06) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 From ed.whyatt at gmail.com Wed Mar 22 06:18:41 2006 From: ed.whyatt at gmail.com (EdWhyatt) Date: 22 Mar 2006 03:18:41 -0800 Subject: Server.sendmail with no "to_addrs" parameter. Message-ID: <1143026321.129185.109310@j33g2000cwa.googlegroups.com> Hi all, I have searched the group with no answer to this particular problem. In my sendmail program, I would like to have the ability to send a mail message with no-one email address in the To field. I do this by adding the mail to the CC field via a header. However, by the time I get to the point of sending the mail, my recipient list is now empty, so I get the "SMTPRecipientsRefused" error. Looking at smtplib.py, this error is raised by: if len(senderrs)==len(to_addrs): # the server refused all our recipients self.rset() raise SMTPRecipientsRefused(senderrs) So, being a "fool" I removed this check. I then got the next error, as self.data(msg) had unexpected data. Can anyone suggest how I can get round this? I have attempted numerous things, like making my recipient list = [''], but Exchange then tried to send the mail to "none at mydomain.local" . Any help would be greatly received. Cheers Ed From __peter__ at web.de Tue Mar 21 17:05:19 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 21 Mar 2006 23:05:19 +0100 Subject: nested for loops References: Message-ID: John Salerno wrote: > Can someone tell me why 'n' in this example isn't 2? > > >>> for n in range(2, 10): > for x in range(2, n): > print 'x =', x, 'n =', n > > > x = 2 n = 3 Hint: >>> range(2, 2) [] Peter From gene.tani at gmail.com Mon Mar 6 12:57:06 2006 From: gene.tani at gmail.com (gene tani) Date: 6 Mar 2006 09:57:06 -0800 Subject: automatic referencing for variables? In-Reply-To: <1141667208.481756.56600@u72g2000cwu.googlegroups.com> References: <1141667208.481756.56600@u72g2000cwu.googlegroups.com> Message-ID: <1141667826.323458.102300@u72g2000cwu.googlegroups.com> sergio at village-buzz.com wrote: > i am SURE i am using the wrong terminology... > > but what i would like to do is something like this: > > pageContent=''' > {toc} > h1. Header Section > h2. Date: > {metadata:date}'''+date+'''{metatdata} > h2. Author: > {metadata:author}Len Sweet{metadata} > h1. Exegesis > {metadata:exegesis}'''+exegesis+'''{metadata} > h1. Text Alive > {metadata:textalive}'''+textAlive+'''{metadata} > h1. Illustrations, Illuminations, Animations: > {metadata:illustrations}'''+illustrations+'''{metadata} > h1. Worship Resources > ''' > > but rather than have: > > '''+variable+''' > > have something a little cleaner.. > > in php, you can do something like > > text="this is text where variable = {variable}"; > ou can use template strings or string formatting on a dict: http://ftp.python.org/doc/lib/node109.html http://diveintopython.org/html_processing/dictionary_based_string_formatting.html From tjreedy at udel.edu Thu Mar 16 21:36:57 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 16 Mar 2006 21:36:57 -0500 Subject: "pow" (power) function References: <1142465999.800332.73050@i39g2000cwa.googlegroups.com><1142470299.753531.269360@j52g2000cwj.googlegroups.com><1142474325.396362.78920@u72g2000cwu.googlegroups.com><1142477182.696407.50340@i39g2000cwa.googlegroups.com> <1142529837.2880.12.camel@dhcp-78-140-229.jpl.nasa.gov> Message-ID: "Mike Ressler" wrote in message news:1142529837.2880.12.camel at dhcp-78-140-229.jpl.nasa.gov... > I have a counterexample. In the original timeit example, 111**111 was > used. When I run that > >>>> timeit.Timer("pow(111,111)").timeit() > 10.968398094177246 >>>> timeit.Timer("111**111").timeit() > 10.04007887840271 >>>> timeit.Timer("111.**111.").timeit() > 0.36576294898986816 > > The pow and ** on integers take 10 seconds, but the float ** takes only > 0.36 seconds. (The pow with floats takes ~ 0.7 seconds). Clearly > typecasting to floats is coming in here somewhere. (Python 2.4.1 on > Linux FC4.) For floats, f**g == exp(log(f**g)) == exp(g*log(f)) (with maybe further algebraic manipulation, depending on the implementation). The time for this should only be mildly dependent on the magnitudes of f and g. The time for i**j, on the other hand, grows at least as fast as log(j). So I should expect comparisons to depend on magnitudes, as you discovered. Terry Jan Reedy From sesquile at gmail.com Thu Mar 9 17:04:45 2006 From: sesquile at gmail.com (mh) Date: 9 Mar 2006 14:04:45 -0800 Subject: Silly import question (__file__ attribute) Message-ID: <1141941885.824586.151680@v46g2000cwv.googlegroups.com> So on most modules I import, I can access the .__file__ attribute to find the implementation. ie: >>> import time >>> time.__file__ '/data1/virtualpython/lib/python2.3/lib-dynload/timemodule.so' >>> import socket >>> socket.__file__ '/data1/virtualpython/lib/python2.3/socket.pyc' This doesn't work on the "thread" module: >>> import thread >>> thread.__file__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute '__file__' A few questions. Why? Where is thread.py or thread.so? (I can't find it). thanks matt From phpbird at gmail.com Wed Mar 15 11:52:16 2006 From: phpbird at gmail.com (JuHui) Date: 15 Mar 2006 08:52:16 -0800 Subject: how to get 20000 html pages content quickly from one server? In-Reply-To: References: <1142439755.840346.181060@p10g2000cwp.googlegroups.com> Message-ID: <1142441536.926474.223870@z34g2000cwc.googlegroups.com> ... I will do it later. but i want to optimize the script first. after useing muti-thread, the time speed up from 8s to 2.3s per page. any other suggestions? From neurogasm at gmail.com Fri Mar 24 17:50:03 2006 From: neurogasm at gmail.com (Kun) Date: Fri, 24 Mar 2006 17:50:03 -0500 Subject: imap folder scanner In-Reply-To: References: Message-ID: Sebastjan Trepca wrote: > A very simple example... > > import imaplib > m = imap.IMAP4() > m.login(username,password) > m.select('myfolder') > status, data = m.search(None,'(SUBJECT "BIKES")') > assert status=='OK', "Error. Message: %s"%data > data = data[0] #you get your results in a list and search returns only > one result > assert data,"No results" > #cool, we have results, but IMAP's search command only returns IDs so > we have to fetch > #msgs now > status,senders = m.fetch(data.replace(' > ',','),'(BODY.PEEK[HEADER.FIELDS (FROM)])') > assert status=='OK', "Error. Message: %s"%data > > Now you just have to parse the "senders" data. There are many examples > about sending emails with python, like this one: > > def send_notice(): > import smtplib > msg = 'we got your mail, indeed' > from email.MIMEText import MIMEText > mail = MIMEText(msg, 'plain', 'utf-8') > mail['From'] =fro='from at example.com' > mail['Subject'] = "Spam machine" > mail['To'] = to = 'to at example.com' > server = smtplib.SMTP('localhost') > errors = server.sendmail(fro, to, mail.as_string()) > server.quit() > > That other program should be very simple to make now. > > Sebastjan > > On 3/24/06, Kun wrote: >> Hey guys, I would like to have a code in python (as simple as possible) >> to scan a specific folder in my mailbox and if the subject is equal to, >> say, 'BIKES', I would like to have the code automatically send the >> SENDER an email saying something like "We have received your Email". >> Furthermore, I would also like to somehow save the sender's email into a >> list which would be compiled by another python program into an html file >> that would show a list of email addresses whose subject matched 'BIKE' >> >> I know i am asking for a lot but since i am new to python, can someone >> help me out with this? Whether its tips or code, i'll be very excited to >> hear your answer. Thanks. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> Thank you very much for your help. I am trying to use your code and currently it works up to the 'fetch', where I am getting the following error: error: FETCH command error: BAD ['Protocol Error: "Specified message set is invalid".'] I guess I do not understand why you have data.replace('',',') and what ",',' means. Thanks so much. Kun From max at alcyone.com Thu Mar 30 02:39:48 2006 From: max at alcyone.com (Erik Max Francis) Date: Wed, 29 Mar 2006 23:39:48 -0800 Subject: difference between .cgi and .py In-Reply-To: <1143701879.632741.6220@g10g2000cwb.googlegroups.com> References: <1143701879.632741.6220@g10g2000cwb.googlegroups.com> Message-ID: amaltasb at gmail.com wrote: > Hi, > I am new to python.. I have uploaded few scripts in my cgi-bin folder, > some with extension .cgi and some with .py. Only how the Web server is configured. > What is the difference between the two extensions.. which one is more > prefered, do it effects performance ?? Unless the server is fundamentally broken, it will make no difference whatsoever. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Physics, as we know it, will be over in six months. -- Max Born (1928) From bencvt at gmail.com Wed Mar 8 23:37:31 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 8 Mar 2006 20:37:31 -0800 Subject: advice on this little script In-Reply-To: <1141877919.475753.27060@j33g2000cwa.googlegroups.com> References: <2bSdncWWK7aINpLZRVn-vA@rcn.net><2bSdncqWK7aJN5LZRVn-vA@rcn.net> <1141877919.475753.27060@j33g2000cwa.googlegroups.com> Message-ID: <1141879051.021695.290570@j52g2000cwj.googlegroups.com> BartlebyScrivener wrote: > What about a console beep? How do you add that? > > rpd Just use ASCII code 007 (BEL/BEEP): >>> import sys >>> sys.stdout.write('\007') Or if you're on Windows, use the winsound standard module. --Ben From greg.kujawa at gmail.com Sat Mar 11 21:44:42 2006 From: greg.kujawa at gmail.com (gregarican) Date: 11 Mar 2006 18:44:42 -0800 Subject: Python IDE: great headache.... In-Reply-To: References: <1142120002.912902.69630@i40g2000cwc.googlegroups.com> Message-ID: <1142131482.688822.171350@i40g2000cwc.googlegroups.com> Sullivan wrote: > IDLE is no longer satisfactory for me. Other IDEs make me very > confused. Really do not know which one to use. > > I use WinXP sp2 for current development. Personally I have gotten used to coding using ActiveState's Komodo. It doesn't get in my way and offers the basic features I am looking for. From webraviteja at gmail.com Fri Mar 31 00:50:51 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 30 Mar 2006 21:50:51 -0800 Subject: Best IDE for Python? In-Reply-To: <1143783179.361616.76750@i39g2000cwa.googlegroups.com> References: <1143783179.361616.76750@i39g2000cwa.googlegroups.com> Message-ID: <1143784251.560076.266630@g10g2000cwb.googlegroups.com> This topic has come up a few dozen times at the least. Please use google to search for the threads. People have their preferences. The best way to choose is to try several by yourself. Most of them are free. http://wiki.python.org/moin/IntegratedDevelopmentEnvironments From tjreedy at udel.edu Mon Mar 13 13:41:57 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 13 Mar 2006 13:41:57 -0500 Subject: Global Threading Lock 2 - Re: "RuntimeError: dictionary changedsize during iteration".. References: <1142214997.549342.123440@e56g2000cwe.googlegroups.com> Message-ID: "robert" wrote in message news:dv3up3$i0c$1 at ulysses.news.tiscali.de... Though mostly ignorant of threading issues, I wonder if the following would work. Derive a class from dict. Define a backup method that sets and unsets a private self.lock. Define setitem and delitem methods that wrap calls to the real methods with while self.lock: sleep(1 second). tjr From wkehowski at cox.net Tue Mar 14 07:23:55 2006 From: wkehowski at cox.net (wkehowski at cox.net) Date: 14 Mar 2006 04:23:55 -0800 Subject: andmap and ormap Message-ID: <1142339035.687474.271120@p10g2000cwp.googlegroups.com> Hello, Does python have andmap and ormap: andmap((lambda t: boolean(t)),L) gives True if boolean(t) is True for all t in L and False otherwise? And ormap((lambda t: boolean(t)),L) gives True if boolean(t) is True for some t in L and False otherwise? One can use a list comprehension like [x for x in L if not(False in map((lambda t: boolean(t)),L))] as an example of selection by andmap, and [x for x in L if (True in map((lambda t: boolean(t)),L))] as an example of selection by ormap. How does one define andmap/ormap so its first argument is a boolean procedure or lambda? def andmap(b,L): if False in map(b,L): return False else: return True def ormap(b,L): if True in map(b,L): return True else: return False Is this good enough? Walter Kehowski From tim at pollenation.net Sun Mar 12 08:34:07 2006 From: tim at pollenation.net (Tim Parkin) Date: Sun, 12 Mar 2006 13:34:07 +0000 Subject: Cheese Shop: some history for the new-comers In-Reply-To: References: <44126523$0$1016$afc38c87@news.optusnet.com.au> <44141D59.6050806@pollenation.net> Message-ID: <4414234F.7020605@pollenation.net> Fredrik Lundh wrote: > Tim Parkin wrote: > > >>For most people 'developers' would mean people developing *with* python, >>not developing python. > > > the page it leads has headings that say "Python Developers Guide" and > "Links for Developers", and contains links about "Development Process", > "Developer FAQ", etc. I think telling people they are in the wrong place isn't quite as good as helping them get to the right place. > I'm convinced that people visiting python.org can distinguish between > "using python to develop stuff" and "developing python", but that's me. Simple user questions (i.e. asking people what they think a 'developers' link would lead to on a programming site) suggests that the majority of people think differently to you. >>Also 'Foundation' could be confused with 'beginners' or 'basic'. > > while "PSF" is completely incomprehensible for someone who doesn't > already know what it is... why even keep it on the front page ? Usability says that people choose the first appropriate link to click on. They will only click on psf if they already know what it is. If it was called *foundation* and they were a beginner then they may well click on 'foundation'. If they wanted to know about the support and community behind python, that material should be obviously placed under 'community' and the information should also be under 'about'. Navigation usability isn't about trying to make every link mean something to every user, it's about making sure that for each use case, a clear path to the information is available. The difference is subtle but important. Calling the link *foundation* goes halfway to solving the problem in the wrong place. > > (give it its own section on the community page instead. the link is > already there; all it needs is a heading and a short blurb). > It was in the community section but most people wanted it back on the top level. Tim Parkin From rrr at ronadam.com Sun Mar 12 12:53:29 2006 From: rrr at ronadam.com (Ron Adam) Date: Sun, 12 Mar 2006 11:53:29 -0600 Subject: Cheese Shop: some history for the new-comers In-Reply-To: References: <44126523$0$1016$afc38c87@news.optusnet.com.au> <44141D59.6050806@pollenation.net> Message-ID: Fredrik Lundh wrote: > Tim Parkin wrote: >> Also 'Foundation' could be confused with 'beginners' or 'basic'. > > while "PSF" is completely incomprehensible for someone who doesn't > already know what it is... why even keep it on the front page ? Looks like a good place for a tool tip, PSF is obviously an acronym, so how about having the full name pop up when the mouse is over it? I think the PSF is important enough to have a link on *every* page. It doesn't need a lot of space, but it should be easy to get to from anywhere on the web site. From rich.churcher at gmail.com Mon Mar 6 01:59:54 2006 From: rich.churcher at gmail.com (Rich Churcher) Date: 5 Mar 2006 22:59:54 -0800 Subject: Popup menus without an associated window Message-ID: <1141628393.951985.250490@v46g2000cwv.googlegroups.com> Is there a way using any of the Python UI toolkits to generate popup menus outside the context of an application? For example, middle-clicking on the desktop shows a list of shortcuts to choose from. Pointers to source examples would be appreciated. -- Cheers, Rich. From caleb.hattingh at gmail.com Thu Mar 30 01:20:25 2006 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 29 Mar 2006 22:20:25 -0800 Subject: python challenge question (string manipulation) In-Reply-To: References: Message-ID: <1143699625.052366.276950@i39g2000cwa.googlegroups.com> Terry That is very succint. Rewriting my shift function given earlier: >>> import string >>> alpha = string.ascii_lowercase >>> print alpha abcdefghijklmnopqrstuvwxyz >>> def shift(lst, n): return [lst[(i+len(lst)-n)%len(lst)] for i,item in enumerate(lst)] >>> print shift(alpha,2) ['y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x'] Shorter and possibly as clear too; thanks! Keep well Caleb From gongcheng_g at hotmail.com Thu Mar 23 06:48:19 2006 From: gongcheng_g at hotmail.com (ChengGong) Date: 23 Mar 2006 03:48:19 -0800 Subject: Probelem about image size and dimensions In-Reply-To: <48fdmpFk0bbbU1@uni-berlin.de> References: <1143109000.672508.175070@t31g2000cwb.googlegroups.com> <48fbg4Fjqn9hU1@uni-berlin.de> <1143111286.875298.277290@z34g2000cwc.googlegroups.com> <48fdmpFk0bbbU1@uni-berlin.de> Message-ID: <1143114499.640227.267150@u72g2000cwu.googlegroups.com> Diez, I asked the administrator that they won't allow me to import Image and PIL in Zope. I am wondering that how can I get the height and width and the size of the image in this situation? Can I just use to get Image's addtributs? Cheng From fuzzyman at gmail.com Fri Mar 24 10:42:15 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Mar 2006 07:42:15 -0800 Subject: path to modules per import statement In-Reply-To: References: <1143127952.665765.155950@j33g2000cwa.googlegroups.com> Message-ID: <1143214935.082256.73760@g10g2000cwb.googlegroups.com> AndyL wrote: > danmcleran at yahoo.com wrote: > >>For instance: "import my.path.module" would load module from > >>./my/path/module.py? > > > > > > Yeah, just do that. I don't understand the question, it works just like > > this today. > > > > I work on rather big set of Python applications: something like 100 .py > files divided into libs and separate sub-applications. > > For now I keep almost everything in one directory but I wish following > structure to be in place: > > app1/ app2/ lib1/ lib2/ lib3/ > There are several approaches. One is to add each of these directories to your sys.path : sys.path.extend(map(os.path.abspath, ['app1/', 'app2/', 'lib1/', 'lib2/', 'lib3/'])) This is a perfectly normal thing to do - so I wouldn't be shy of it. Another is to add an empty file called ``__init__.py`` to each of these directories. This makes each directory a 'package'. You can then do : import app1.module My module `pathutils `_ contains a third approach that *does* allow you to specify the location of your module. It's a less suitable approach in your case however. HTH Fuzzyman http://www.voidspace.org.uk/python/index.shtml > > and be able to import from each app[12] all the libs. I do not want to > touch existing code to prefix all the import places with lib[123] nether > I want to play with sys.path.append too much. > > > A. From grante at visi.com Wed Mar 1 11:14:32 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 01 Mar 2006 16:14:32 -0000 Subject: Use empty string for self References: <1141170846.619246.163470@t39g2000cwt.googlegroups.com> <120a94q7qnhb97@corp.supernews.com> Message-ID: <120bi38s9ms3i34@corp.supernews.com> On 2006-03-01, John Salerno wrote: > I do get it. I think I will just have to get used to seeing > the 'self' argument but understanding that it's not really > something that is always passed in. But it _is_ always passed to the function. You can even pass it explicity when you call the method if you want: #!/usr/bin/python class MyClass: def mymethod(self,p1,p2): print self,p1,p2 instance = MyClass() MyClass.mymethod(instance,1,2) instance.mymethod(1,2) The two calls are equivalent. > I'm trying to train myself to see > > def doittoit(self) as def doittoit() You would be misleading yourself. > Of course, that might not be a good strategy, because I know > when it isn't used as an instance method (is that C > terminology?), then you must explicitly pass the self > argument. Exactly. -- Grant Edwards grante Yow! I guess we can live at on his POT FARM in HADES!! visi.com From steve at holdenweb.com Sat Mar 18 17:07:48 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 18 Mar 2006 22:07:48 +0000 Subject: How to convert In-Reply-To: <1142687798.038654.12460@i39g2000cwa.googlegroups.com> References: <1142687566.540612.83480@z34g2000cwc.googlegroups.com> <1142687798.038654.12460@i39g2000cwa.googlegroups.com> Message-ID: JuHui wrote: >>>>10/3.0 > > 3.3333333333333335 > The above value is a float, not a long ... >>>>int(10/3.0) > > 3 > >>> int(1l) 1 >>> 100000000000000000000 100000000000000000000L >>> 100000000000000000000/1000000000000000000 100L >>> int(100000000000000000000/1000000000000000000) 100 >>> regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From andrewfelch at gmail.com Thu Mar 9 19:32:24 2006 From: andrewfelch at gmail.com (andrewfelch at gmail.com) Date: 9 Mar 2006 16:32:24 -0800 Subject: Best way to have a for-loop index? Message-ID: <1141950744.482666.4430@j33g2000cwa.googlegroups.com> I write a lot of code that looks like this: for myElement, elementIndex in zip( elementList, range(len(elementList))): print "myElement ", myElement, " at index: ",elementIndex My question is, is there a better, cleaner, or easier way to get at the element in a list AND the index of a loop than this? TIA, Andrew From johnjsal at NOSPAMgmail.com Sat Mar 25 16:57:55 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 25 Mar 2006 16:57:55 -0500 Subject: is mysqlsb compatible with MySQL 5.0? In-Reply-To: <1143322764.631997.10900@v46g2000cwv.googlegroups.com> References: <1143322764.631997.10900@v46g2000cwv.googlegroups.com> Message-ID: Ravi Teja wrote: > Yes! It does. > > Assuming that you are not terribly bandwidth constrained, isn't it > easier for you to try it > yourself on your own machine than wait for other people to assure you, > given that both are free and pretty much run on any platform? > Yeah, actually I went ahead and installed them both to try it out, but Norton Internet Security is causing huge problems with the MySQL setup. Even when I disable it, it won't let me get past the configuration steps. :( From lists at elehack.net Thu Mar 2 09:33:30 2006 From: lists at elehack.net (Michael Ekstrand) Date: Thu, 2 Mar 2006 08:33:30 -0600 Subject: Suggestions for documentation generation? In-Reply-To: <1141301177.328114.69350@i39g2000cwa.googlegroups.com> References: <1141240014.302680.78850@z34g2000cwc.googlegroups.com> <1141301177.328114.69350@i39g2000cwa.googlegroups.com> Message-ID: <20060302083330.25aa61f3.lists@elehack.net> On 2 Mar 2006 04:06:17 -0800 "kpd" wrote: > Thanks - I took at both. Also at 'percepts', which I used a long time > ago (had forgotten about it). Percepts has a great little java applet > for viewing the class hierarchy. I don't think it works for python, > just C++ though. Looks like doxygen will fit the bill. An excellent choice IMHO. Doxygen has recently added support for Python, so if there is pure-Python code interfacing with the rest of your work, that can be documented also. - Michael -- mouse, n: a device for pointing at the xterm in which you want to type. -- Fortune From bearophileHUGS at lycos.com Thu Mar 9 15:31:17 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 9 Mar 2006 12:31:17 -0800 Subject: First script, please comment and advise In-Reply-To: References: <1141917596.011498.311500@p10g2000cwp.googlegroups.com> <1141920446.935210.260650@j52g2000cwj.googlegroups.com> Message-ID: <1141936277.648924.119020@z34g2000cwc.googlegroups.com> This is different too, but maybe a little better than my last version: from random import shuffle from itertools import groupby def scramble_text(text): """Return the words in input text string scrambled, except for the first and last letter.""" def scramble(word): if len(word) < 4: return "".join(word) core = word[1:-1] shuffle(core) return "".join([word[0]] + core + [word[-1]]) return "".join(scramble(list(g)) for _,g in groupby(text, str.isalpha)) print scramble_text(scramble_text.__doc__) Just, we can discuss a lot, but it's probably of little use, because different programmers have different style of programming. If you take someone that is expert in Lisp or Java (and with some Python experienxe) you can probably find other possibile solutions of this same little problem. Sometimes you can ask them to write more pythonic programs, but you cannot ask them to program exactly as you do. I can answer some of your points, but it's just a relaxed discussion... >Luckily this is Python, not Pascal :) I agree that Python isn't a Pascal-like language, they are usually compiled, so nested functions have less overhead, and there are other differences. But Object Pascal has some good parts too, some things are better than Python ones. Like the sintax of bitwise operators and %-like formatting, some parts of the the I/O, etc. Many languages are designed by intelligent people. Lisp, Mathematica, Perl, Ruby, Delphi, Haskell, D, Smalltalk, OCaml, ML aren't Python, so you can't copy them, but sometimes they can teach you how to better program in Python. >1. The fact that one function calls the other doesn't mean they're "logically nested".< In this situation they were logically nested, because the scramble_word is a function needed by another one only, in Java the scramble_word becomes a (private) method of a text scrambling class; this means it is nested and hided inside a class. Pascal languages were pre-OOP and they used nested function for similar purposes, that it to hide and structure functions inside other ones, that in OO languages like Java, ObjectPascal, Python, etc. you usually do with classes. >2. The helper function is useful on its own, so it is a waste to hide it inside another. Good luck at finding other uses for that function :-) >3. The nested function makes the enclosing function harder to read. I can read it fine, but I can understand that you are probably less used to nested functions, so what's true for me isn't true for you. >4. I don't buy the namespace pollution argument, we have modules after all. I presume Guido agrees that function nesting is another way to avoid namespace pollution :-) There are many ways to do the same thing, to avoid pollution in one module. >5. Overhead: every time a new function object is created, for no good reason. (But you save a global name lookup, yet that doesn't appear to weigh up against the function def. [*])< This function isn't going to be used much. If later I find I have to optimize it, then I don't use a nested function at all, and I just use a single function that does everything. But until such optimization needs, I choose the most logical structuration of the program, that allows me better programming. >To me, nested functions (in Python) are *only* helpful when using closures. If you're not using the enclosing scope, you're just obfuscating things.< Note that until recent time, Python nested scopes were managed quite differently (in a bad way), and yet, they regarded the function nesting useful enough to be kept anyway. I don't agree with you, but every programmer is diffent, because their story is different. If you have learnt to program with Java/C then you probably don't like nested functions. If you started with a Pascal-like language then probably you like that nesting more. If you start with a Scheme/Lisp background you progrably write Python programs like the good Norvig: http://aima.cs.berkeley.edu/python/utils.py And so on... Maybe other people here can say what they think about this topic, it's just a relaxed discussion. Bye, bear hugs, bearophile From python.list at tim.thechases.com Sun Mar 19 10:39:36 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 19 Mar 2006 09:39:36 -0600 Subject: Initializing a list of lists In-Reply-To: <1142782140.389645.23500@z34g2000cwc.googlegroups.com> References: <1142782140.389645.23500@z34g2000cwc.googlegroups.com> Message-ID: <441D7B38.4090005@tim.thechases.com> > The above construct works if I have only few items, but if I have many, > I'd prefer to write > >>>>N =3 >>>>x =N*[[0]] >>>>x > > [[0], [0], [0]] > > If I now try extending the lists indepently, I cannot, as they all > point to the same list object > >>>>x[0].append(1) >>>>x > > [[0, 1], [0, 1], [0, 1]] > > Is there a simple way to create a list of independent lists? My first thought would be >>> N = 10 >>> x = [[0] for _ in range(N)] >>> x[0].append(1) >>> x [[0, 1], [0], [0], [0], [0], [0], [0], [0], [0], [0]] HTH, -tkc From sullivanz.pku at gmail.com Fri Mar 31 06:17:12 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 31 Mar 2006 03:17:12 -0800 Subject: How to search HUGE XML with DOM? Message-ID: <1143803831.939208.190850@v46g2000cwv.googlegroups.com> a relation database has admiring search efficiency when the database is very big (several thousands or tens of thousands of records). But my current project is based on XML, for its tree-like data structure has much more flexibility; and DOM, which could be manipulated just like a tree. However, how to establish such a XML data base for search when it contains 10,000 records (One record usually contain 10~30 tags) or more? My search needs: 1. Search and return all the record (an element) with specific id. 2. Search and return all the record whose child nodes has a specific id or attribute. the xml.dom.minidom object is too slow when parsing such a big XML file to a DOM object. while pulldom should spend quite a long time going through the whole database file. How to enhance the searching speed? Are there existing solution or algorithm? Thank you for your suggetion... From olanglois at quazal.com Mon Mar 20 14:46:35 2006 From: olanglois at quazal.com (Olivier Langlois) Date: Mon, 20 Mar 2006 14:46:35 -0500 Subject: String comparison question Message-ID: <400BDC416E2A0042AA35DF3919BB8A5115E679@mail.mtl.proksim.com> Hi Michael, Normalizing the whitespace is what I was looking to do. I guess that that aspect of my original query was not enough clear. But with either solutions, I get the result I wanted. Greetings, Olivier Langlois http://www.quazal.com > -----Original Message----- > Fredrik Lundh wrote: > > > > >>>> " hello world ".split() > > ['hello', 'world'] > > a.split() == b.split() is a convenient test, provided you want to > normalize > whitespace rather than ignore it. I took the OP's requirements to mean > that > 'A B' == 'AB', but this is just a guess. > > > Michael From gene.tani at gmail.com Sat Mar 25 10:10:31 2006 From: gene.tani at gmail.com (gene tani) Date: 25 Mar 2006 07:10:31 -0800 Subject: What's The Best Editor for python In-Reply-To: References: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> Message-ID: <1143299430.958474.107900@i39g2000cwa.googlegroups.com> Christoph Zwerschke wrote: > Just because nobody has mentioned them so far: > > - SciTe is a perfect editor for Pyhton on Win and Linx > - PyScripter is a wonderful IDE (but only on Win) > - DrPython is a nice platform independent editor/mini-IDE > http://www.artima.com/forums/flat.jsp?forum=106&thread=148389&start=0&msRange=15 http://activestate.com/Products/Komodo/?utm_source=home_page&utm_medium=banner&utm_campaign=Komodo http://wingware.com/ Also vim, emacs, jedit or eclipse, textmate, Leo, Kate, From fredrik at pythonware.com Fri Mar 17 01:57:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 17 Mar 2006 07:57:35 +0100 Subject: Is there a python library to parse C++ code file? References: <1142566046.428804.142440@p10g2000cwp.googlegroups.com> Message-ID: Allerdyce.John at gmail.com wrote: > Is there a python library to parse C++ code file? > If yes, can you please tell me where is it? depends on how you want to parse the file, and what information you want to extract. without more details, I'd recommend http://www.gccxml.org/HTML/Index.html combined with some python xml library, e.g. http://www.effbot.org/zone/element-index.htm http://www.effbot.org/zone/element-iterparse.htm which gives you something like: http://www.boost.org/libs/python/pyste/ which might be a good thing to look at before you start ... or maybe you had something much simpler in mind ? From jedp at ilm.com Wed Mar 29 19:08:59 2006 From: jedp at ilm.com (Jed Parsons) Date: Wed, 29 Mar 2006 16:08:59 -0800 Subject: ldap usage In-Reply-To: References: Message-ID: <442B219B.3030108@ilm.com> Hi, Michael, Thanks very much for your response. I think I can work it out now. >> authenticated = False > ^^^ > Identiation is wrong here. Yes, sorry about that - doesn't always work on this email client :( As an addendum, I discovered one little gotcha, namely that this: l.bind_s(username, password, ldap.AUTH_SIMPLE) throws an ldap.INVALID_CREDENTIALS error if the password contains the wrong text, but works if the password is empty. I guess this is tantamount to binding as ("", ""), but I wasn't expecting it; I figured if a username was specified, the password would have to agree. So my little authentication example also needs to test for empty passwords. Neither here nor there, really; just thought I'd mention it since I ran into it. Now I'm off to check out the Demo/*.py scripts you pointed me to. Thanks again. Cheers! j Michael Str?der wrote: > Jed Parsons wrote: >> import ldap >> l = ldap.open('our.ldap.server') >> try: >> l.bind_s(username, password, ldap.AUTH_SIMPLE) >> authenticated = True >> except: >> authenticated = False > ^^^ > Identiation is wrong here. > > Also I'd recommend to catch the ldap.LDAPError exceptions more > specifically (ldap.INVALID_CREDENTIALS indicates wrong password): > > try: > l.bind_s(username, password, ldap.AUTH_SIMPLE) > except ldap.INVALID_CREDENTIALS: > authenticated = False > else: > authenticated = True > >> But this uses the plaintext of the user's password. > > Yes, since this is a LDAP Simple Bind Request as defined in RFC 2251. > >> Is there a proper >> way to send a cryptographic hash to the ldap server? Or do I have to >> negotiate this through an ssl tunnel or something? > > SSL (either LDAPS or StartTLS extended operation) is one possibility to > secure the whole connection including bind requests (see > Demo/initialize.py). > > Another option is to use SASL with DIGEST-MD5 if your server supports it > (see Demo/sasl_bind.py) and has the cleartext passwords available. Other > options with SASL, e.g. GSSAPI (Kerberos), exist but highly depends on > your IT infrastructure and LDAP server configuration. > > Just follow-up here or on the python-ldap-dev mailing list if you have > further problems. > > Ciao, Michael. -- Jed Parsons Industrial Light + Magic (415) 746-2974 grep(do{for(ord){(!$_&&print"$s\n")||(($O+=(($_-1)%6+1)and grep(vec($s,$O++,1)=1,1..int(($_-6*6-1)/6))))}},(split(//, "++,++2-27,280,481=1-7.1++2,800+++2,8310/1+4131+1++2,80\0. What!?"))); From __peter__ at web.de Fri Mar 24 07:44:42 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 24 Mar 2006 13:44:42 +0100 Subject: encoding problems =?ISO-8859-1?Q?=28=E9_and_=E8=29?= References: <44230fa6$1@news.eftel.com> <4423dacb$1@news.eftel.com> Message-ID: John Machin wrote: > 0x00d0: ord('D'), # ? > 0x00f0: ord('o'), # ? > Icelandic capital eth becomes D, OK; but the small letter becomes o!!! I see information flow from Iceland is a bit better than from Armenia :-) > Some of the transformations are a little unfortunate :-( The OP, as you pointed out in your first post in this thread, has more pressing problems with his normalization approach. Lastly, even if all went well, turning a list of French addresses into an ascii-uppercase graveyard would be a sad thing to do... Peter From steve at holdenweb.com Mon Mar 6 16:17:02 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 06 Mar 2006 21:17:02 +0000 Subject: Pyserial again In-Reply-To: <1141675566.162480.148260@v46g2000cwv.googlegroups.com> References: <1141661808.753184.157150@e56g2000cwe.googlegroups.com> <1141665448.418740.167910@i40g2000cwc.googlegroups.com> <120ossf55scsj8b@corp.supernews.com> <1141675566.162480.148260@v46g2000cwv.googlegroups.com> Message-ID: Luca wrote: >>and than i store the read data in a textctrl. > > > That's got nothing to do with pyserial. > > Ok i know but for this reason i put : > > Another point is the textctrl: it store only the first byte and not > the > other why?, the byte are like 22 and all are readed > ------------------------------------------------------------------------------------------------------------------------------- > No clue. I don't know what "textctrl" is or what it's supposed > to do. > > a = ser.readline() > a = self.textCtrl3.SetValue(a + ' ') > > For my bad understanding is clear > > ------------------------------------------------------------------------------------------------------------------------------- > What makes you think the port closed? > > Sniffing the data with serial port monitor i see that the > >>answer is ok but after the answer the port close, why? > > > The serial port monitor write com port close. > > ---------------------------------------------------------------------------------------------------------- > > > Dear Grant > > As you know i'm not a programmer, but i try to do this in my free time. > Probably you have reason to write: > > The code you post is irrelevant. > > But i try to do my best as in my possibility. > > I think that in any case you can't run my code if you haven't the same > device that i have. > > So i don't want that you loose time with my stupid question, i'm sure > you have a lot of better things to do that help a beginner like me. > > In any case thanks for your help, and you cordility. > > Best Regards > > Luca > Luca: Grant was just pointing out that we can't tell you what's wrong with your code if we can't see it. Nobody expects you to be an experienced programmer. We just aren't understanding you at the moment. You say "the port closes", but this doesn't really have any standard meaning - can you not send data any more? Please be patient and answer our questions. We *are* trying to help! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From joel.hedlund at gmail.com Fri Mar 10 11:24:17 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Fri, 10 Mar 2006 17:24:17 +0100 Subject: why use special config formats? In-Reply-To: References: <1142002082.976945.261900@e56g2000cwe.googlegroups.com> <1142004363.863051.29090@j33g2000cwa.googlegroups.com> Message-ID: I agree with Steve and I agree Sybren. Also: This is a Bad Idea, since you should never add more complexity than needed. Imports, computation, IO and so on are generally not needed for program configuration, so standard configfile syntax should therefore not allow it. Otherwise you may easily end up with hard-to-debug errors, or even worse - weird program behavior. /Joel From robert.kern at gmail.com Fri Mar 17 20:16:59 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 17 Mar 2006 19:16:59 -0600 Subject: SVD question In-Reply-To: <1142643103.099002.284190@p10g2000cwp.googlegroups.com> References: <1142643103.099002.284190@p10g2000cwp.googlegroups.com> Message-ID: smritibhagat at gmail.com wrote: > Hi! > I have been trying to figure this out, and need help... > How do I compute an orthogonal complement of a matrix using SVD? On the chance that this is homework, I will only point out that Golub and van Loan's book _Matrix Computations_ is essential reading if you are doing, well, matrix computations. > Is there a python lib function or code that does this? numpy has SVD. http://numeric.scipy.org -- Robert Kern robert.kern at gmail.com "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 7abc at sogetthis.com Fri Mar 17 14:40:25 2006 From: 7abc at sogetthis.com (PofN) Date: 17 Mar 2006 11:40:25 -0800 Subject: Xah's Edu Corner: The Concepts and Confusions of Pre-fix, In-fix, Post-fix and Fully Functional Notations References: <1142490052.127055.50130@v46g2000cwv.googlegroups.com> <1142586590.059072.64940@z34g2000cwc.googlegroups.com> Message-ID: <1142624425.509832.27820@p10g2000cwp.googlegroups.com> Dinko Tenev wrote: > If only someone could persuade this guy to stay away from CS... I still hope that at some point in time he will manage to tender his nomination for the darvin award. You can't rationalize with that troll, because there is nothing between his ears capable of catching a clue. From tim at pollenation.net Sun Mar 12 09:14:02 2006 From: tim at pollenation.net (Tim Parkin) Date: Sun, 12 Mar 2006 14:14:02 +0000 Subject: Cheese Shop: some history for the new-comers In-Reply-To: References: <44126523$0$1016$afc38c87@news.optusnet.com.au> <44141D59.6050806@pollenation.net> <4414234F.7020605@pollenation.net> Message-ID: <44142CAA.9080407@pollenation.net> Fredrik Lundh wrote: >Tim Parkin wrote: > > > >>Simple user questions (i.e. asking people what they think a 'developers' >>link would lead to on a programming site) suggests that the majority of >>people think differently to you. >> >> > >so where's this mythical user group that you're using for the site testing ? > > > > > > freinds and colleagues both online and off.. Some of whom are python programmers, most not. Without a budget for 'comprehensive testing' then the next best thing is asking people, at least you'll generally get rid of the big bloopers.. it's typically referred to as guerilla testing and whilst not scientific, it's better than nothing at all. Tim Parkin From rridge at csclub.uwaterloo.ca Tue Mar 28 18:18:10 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 28 Mar 2006 15:18:10 -0800 Subject: Difference between 'is' and '==' In-Reply-To: References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <4427d287$0$38669$edfadb0f@dread12.news.tele.dk> Message-ID: <1143587890.555474.163570@e56g2000cwe.googlegroups.com> Felipe Almeida Lessa wrote: > That said, you can do thinks like: > >>> import socket > >>> a = socket.AF_UNIX > >>> a is socket.AF_UNIX > True > > That kind of constants can be used with "is". But if don't want to be > prone to errors as I do, use "is" only when you really know for sure > that you're dealing with singletons. It's only safe to to compare address family values with socket.AF_UNIX using "is", if small integers are guaranteed to be singletons, and socket.AF_UNIX has one of those small values. Otherwise, address family values equal in value to socket.AF_UNIX can be generated using different objects. There's no requirement that the socket module or anything else return values using the same object that the socket.AF_UNIX constant uses. Consider this example using the socket.IPPROTO_RAW constant: >>> socket.getaddrinfo("localhost", None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)[0][2] is socket.IPPROTO_RAW False >>> socket.getaddrinfo("localhost", None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)[0][2] == socket.IPPROTO_RAW True Ross Ridge From eric.pederson at gmail.com Sun Mar 12 13:36:15 2006 From: eric.pederson at gmail.com (EP) Date: 12 Mar 2006 10:36:15 -0800 Subject: Class attributes newbie question (before I join a cargocult) Message-ID: <1142188575.187032.61390@v46g2000cwv.googlegroups.com> Hi, This is likely a stupid question, but I am confused about what is going on with class attributes as far as whether they "stick". I ran across this in a program I am writing, but have reproduced the behavoir below - can someone point me in the right direction (thanks): class AttStickiness(object): def __init__(self, myname="", mysex=""): self.name=myname self.sex=mysex def changeSex(self, newsex=""): self.mysex=newsex return self.mysex def changeName(self, newname=""): self.name=newname return self.name def whoAmI(self): return self.name, self. sex >>> me=AttStickiness("Eric","Male") >>> me.whoAmI() ('Eric', 'Male') >>> me.changeName("Jimbo") 'Jimbo' >>> me.whoAmI() ('Jimbo', 'Male') >>> me.changeSex("female") 'female' >>> me.whoAmI() ('Jimbo', 'Male') [while it is comforting to know my sex isn't so easily changed, this has confounded me in real code] thx, Eric From no-spam at no-spam-no-spam.com Thu Mar 30 11:30:17 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 30 Mar 2006 18:30:17 +0200 Subject: "module pointer files" for import (now and py2.5) ? Message-ID: I want to occasionally do a "redirected" import of a python module which is located offside of the legacy sys.path (Windows) - for example a tool is maintained within "cgi-bin" web stuff (while I do not want to add that whole folder's stuff to the sys.path) .pth adds only directories to the python path. is there a convenient/short method to create a python "module pointer" (file) to such module - maybe just create such pointer file somewhere on the python path (in my "sitetools") ? If no clean method, what is the best ad-hoc trick? ( In addition to what mere UNIX links would do, it should be consistent pythonic: such module can import neighbor modules (relatively), create the .pyc's next to the code... ) Is such stuff more easy and consistent with py2.5's relative imports? Are such module pointers maybe supported somehow in py2.5? robert From rowen at cesmail.net Wed Mar 29 13:09:06 2006 From: rowen at cesmail.net (Russell E. Owen) Date: Wed, 29 Mar 2006 10:09:06 -0800 Subject: Problem w/Tkinter on 2.5 (Panther) References: Message-ID: I don't know, and I'm sorry this isn't more helpful, but...if you don't get an answer here, I suggest you post to the python apple mailing list. If you prefer a newsgroup interface (as I do), use gmane's news server and subscribe to gmane.comp.python.apple (you may still have to join the mailing list to post -- I'm not sure -- but if so, you can disable mail delivery). -- Russell In article , "w chun" wrote: > i've built a Python 2.5a0 interpreter on my iBook using gcc 3.3-1666 > using the tarball from last nite...... From johnjsal at NOSPAMgmail.com Mon Mar 20 10:42:43 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 20 Mar 2006 15:42:43 GMT Subject: what's the general way of separating classes? Message-ID: From my brief experience with C#, I learned that it was pretty standard practice to put each class in a separate file. I assume this is a benefit of a compiled language that the files can then be grouped together. What I'm wondering is how is this normally handled in Python? Is it normal for classes to be put in separate modules? It seems like this can get out of hand, since modules are separate from one another and not compiled together. You'd end up with a lot of import statements. Are related classes put into a single module then? Or is there some recommended method for how to handle this? Thanks. From kent at kentsjohnson.com Fri Mar 3 07:05:22 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 03 Mar 2006 07:05:22 -0500 Subject: in need of some sorting help In-Reply-To: <1141360027.951400.173750@j33g2000cwa.googlegroups.com> References: <1141275649.856712.313540@p10g2000cwp.googlegroups.com> <1141360027.951400.173750@j33g2000cwa.googlegroups.com> Message-ID: <44082c51$1_1@newspeer2.tds.net> ianar? wrote: >> you did make me understand a way to sort this thing finally: sort by > base path then by full path, which is how i came up with: > > files.sort(key=lambda x: x.lower()) > files.sort(key=lambda x: os.path.dirname(x)) > > well actually i am sorting first by full name, then by base, taking > advantage of python2.4's stable sort(). > > If you can think of a more efficient (faster) way of doing this please > let me know. i'm not crazy about having to sort this list twice, it can > get pretty big (50,000 entries) Use a key function that returns a tuple of the two values you want to sort on: def make_key(f): return (os.path.dirname(f), f.lower()) files.sort(key=make_key) Kent From bellman at lysator.liu.se Sun Mar 19 06:58:38 2006 From: bellman at lysator.liu.se (Thomas Bellman) Date: Sun, 19 Mar 2006 11:58:38 +0000 (UTC) Subject: How do I use the subprocess module with mswindows? References: Message-ID: Darren Dale wrote: > import subprocess > process = subprocess.Popen(['dir'], stderr=subprocess.STDOUT, > stdout=subprocess.PIPE) > stat = process.wait() > print process.stdout.read() You have already gotten the answer to why 'dir' doesn't work for you, but there is a bug hiding in that code that you might not notice in simple tests. You are waiting for your subprocess to complete without reading away what it prints. That will quickly fill the buffer available in the pipe between you and the subprocess, and the subprocess will block. Try calling Popen() with something that prints more data, like ['find', '/', '-print'] on a Unix box, and you will notice that problem. What you should do is: output = process.stdout.read() stat = process.wait() print output Or, you could use the .communicate() method on the Popen object instead of .stdout.read(). If you find yourself juggling several subprocesses running in parallel, producing and/or consuming data "incrementally", or just trying to handle both sending input to and reading output from a single subprocess without deadlocking, you may be helped by using my asyncproc module, which you can download from http://www.lysator.liu.se/~bellman/download/asyncproc.py I suspect that it only works on Unix, though. -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "Beware of bugs in the above code; I have ! bellman @ lysator.liu.se only proved it correct, not tried it." ! Make Love -- Nicht Wahr! From singletoned at gmail.com Wed Mar 29 03:47:09 2006 From: singletoned at gmail.com (Ed Singleton) Date: Wed, 29 Mar 2006 09:47:09 +0100 Subject: Doc suggestions (was: Why "class exceptions" are not deprecated?) In-Reply-To: References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com> <1143070060.384366.25480@z34g2000cwc.googlegroups.com> <1143574346.354680.136060@i39g2000cwa.googlegroups.com> Message-ID: <34bb7f5b0603290047o21b9a1b7k64cdd206f604fc10@mail.gmail.com> On 29/03/06, Fredrik Lundh wrote: > rurpy at yahoo.com wrote > > write a tutorial as good as what is already there. But what I can > > do is report problems I find when using it, and make suggestions > > about how to avoid those problems. > > There's no shortage of ideas -- nor people who can write a tutorial > that's better than the current one (which is far from optimal, mostly > thanks to a zillion peephole edits over the years). There's a shortage > of volunteer time, though. That's why the "I'm just the idea guy, > someone else will have to provide the hundreds of hours required > to implement my idea" arguments are so offensively meaningless. I'm not entirely sure there is a shortage of people who want to volunteer, just that a lot don't know that they can volunteer, and those that do can't make a huge time commitment or don't have the confidence. I think there's quite a lot of people who would be happy to help out as and when they could (particularly with small edits like the one mentioned), if they were sure someone else was going to double check that they hadn't accidentally written garbage. This would be a perfect situation for a wiki. I think it would be a good experiment to have a wiki containing the documentation (separate from the main documentation and clearly marked experimental for the moment), and to see if it did self-organise as wikis often do. Beginners like rurpy could add comments when they don't understand a paragraph, more confident people could attempt to correct the paragraph, and every now and then an advanced person could scan through it and make sure it was truly accurate. It would greatly reduce the work need by the people currently responsible for documentation (they just have to read through and make sure things are correct) and if a page has been significantly improved by the community and double checked by an expert, it could be promoted to the official version of the documentation. If the whole thing descends into chaos, the wiki (pages) could just be deleted and we continue with the current system. As Python has such an excellent community, it would be a shame not to give them more responsibility in this area, and this system seems to be working quite well for many python projects (many just use the wiki in Trac). Ed (I'm actually tempted to just copy and paste each page from the tutorial into the current wiki but I'd hate for it all to be deleted after doing that). From claudio.grondi at freenet.de Thu Mar 30 18:35:48 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 31 Mar 2006 01:35:48 +0200 Subject: Identifying filled circles in a scanned image In-Reply-To: References: Message-ID: Douglas Douglas wrote: > Hi everybody. > > I have a paper form that I scan into an image. My user fills some circles in > this paper form using black ink. Every form has ten rows with five circles each > and the user fills only one circle for each row. > > I was wondering if I could use the Python Imaging Library to process these > forms. I know the Image class is really powerful, but I can't think of a way of > how to locate wich circle was filled. > > Could anybody please give me an advice on this? If you know the position of the circles in the picture (if you scanned properly you know it), you can test the mean darkness of the pixels within the circle (dark pixels: filled circle, bright pixels: not filled one). PIL allows access to any single pixel value (e.g. triple of values in case of RGB) in the picture, so, that you can test it against self-chosen threshold values. It could be helpful to try to be a bit more specific about your problem (you have read the PIL tutorial, right?) if this above is not what you are looking for. Claudio > > Thanks. > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com From Serge.Orlov at gmail.com Sun Mar 12 16:33:49 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 12 Mar 2006 13:33:49 -0800 Subject: Customizing character set conversions with an error handler In-Reply-To: References: Message-ID: <1142199228.960882.74490@u72g2000cwu.googlegroups.com> Jukka Aho wrote: > When converting Unicode strings to legacy character encodings, it is > possible to register a custom error handler that will catch and process > all code points that do not have a direct equivalent in the target > encoding (as described in PEP 293). > > The thing to note here is that the error handler itself is required to > return the substitutions as Unicode strings - not as the target encoding > bytestrings. Some lower-level gadgetry will silently convert these > strings to the target encoding. > > That is, if the substitution _itself_ doesn't contain illegal code > points for the target encoding. > > Which brings us to the point: if my error handler for some reason > returns illegal substitutions (from the viewpoint of the target > encoding), how can I catch _these_ errors and make things good again? > > I thought it would work automatically, by calling the error handler as > many times as necessary, and letting it work out the situation, but it > apparently doesn't. Sample code follows: > > > # So the question becomes: how can I make this work > # in a graceful manner? > change the return statement with this code: return (substitution.encode(error.encoding,"practical").decode( error.encoding), error.start+1) -- Serge From fredrik at pythonware.com Mon Mar 6 12:10:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 6 Mar 2006 18:10:56 +0100 Subject: Need help initializing a list or tuple. References: <1141664498.539402.43160@e56g2000cwe.googlegroups.com> Message-ID: "KraftDiner" wrote: > I need a matrix of 256 x 256 unsigned short values... > The matrix can be implemented as a list of lists or a tuple... > So for example: > [[1][2][3], [4][5][6], [7][8][9]] > or > ((1,2,3),(4,5,6), (7,8,9)) > > This is what I have so far but its not working... > > a = [][] > for i in range(0,256): > for j in range(0,256): > a[i][j] = i**2 this might help: http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list From felipe.lessa at gmail.com Thu Mar 23 10:48:41 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Thu, 23 Mar 2006 12:48:41 -0300 Subject: Python has a new Logo In-Reply-To: <1143128619.670174.282160@t31g2000cwb.googlegroups.com> References: <1143128619.670174.282160@t31g2000cwb.googlegroups.com> Message-ID: <1143128921.8303.3.camel@kenshin> Em Qui, 2006-03-23 ?s 07:43 -0800, Xah Lee escreveu: > Python has a new logo! Really? :) > See http://python.org/ > > And it is a fantastic logo. LOL, sorry for the trolling, but we already had loads of (good) discussions about it some time ago... -- Felipe. From jiri.juranek at kctdata.cz Sat Mar 18 13:06:13 2006 From: jiri.juranek at kctdata.cz (jiri.juranek at kctdata.cz) Date: 18 Mar 2006 10:06:13 -0800 Subject: ipv6 validation Message-ID: <1142705173.912345.301840@g10g2000cwb.googlegroups.com> Hello, is there any common function for validation if string contains valid ip address(both ipv4 and ipv6)? Or does sb wrote some regular expression for this? thanks J From cito at online.de Mon Mar 20 06:53:09 2006 From: cito at online.de (Christoph Zwerschke) Date: Mon, 20 Mar 2006 12:53:09 +0100 Subject: ** Operator In-Reply-To: <1hcgw5p.1ufznwe1lxeagfN%aleaxit@yahoo.com> References: <1142833145.976550.104830@v46g2000cwv.googlegroups.com> <1142833540.860154.137040@u72g2000cwu.googlegroups.com> <1hcgw5p.1ufznwe1lxeagfN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Sathyaish wrote: > >> I tried it on the interpreter and it looks like it is the "to the power >> of" operator symbol/function. Can you please point me to the formal >> definition of this operator in the docs? > > http://docs.python.org/ref/power.html I think this should be also mentioned in the Built-In Functions section of the Library Reference. Probably most users do not read the Language Reference (since the main menu says it's "for language lawyers" and yes, it is not really fun to read). In the explanation about pow() at http://docs.python.org/lib/built-in-funcs.html, the notation 10**2 is suddenly used, without explaining that it is equivalent to pow(10,2). I think this could be improved in the docs. -- Christoph From martin at v.loewis.de Thu Mar 9 09:08:36 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 09 Mar 2006 15:08:36 +0100 Subject: String functions: what's the difference? In-Reply-To: <978190B85Wile.E.Coyote@62.58.50.216> References: <978190B85Wile.E.Coyote@62.58.50.216> Message-ID: <441036E4.6040907@v.loewis.de> Harro de Jong wrote: > I've tried all three, but the function is so small (test a single letter) I > can't measure the difference. I'm using time.time() to see how long it takes to > execute the function. > I could use a loop to increase execution time, but then I might be measuring > mostly overhead. Still, this is what you should do. Try the timeit.py module; it does the loop for you. Surprisingly, one of the faster ways to do a loop is nones = [None]*10000000 for x in nones: This is fast because no Python integers are created to implement the loop. > I'd expect the third option to be the fastest (involves looking up 3 values, > where the others have to iterate through a-z), but am I right? Just measure it for yourself. I just did, and the third option indeed came out fastest, with the "in" operator only slightly slower. > And reasons to prefer one? For what purpose? To find out whether a letter is lower-case? Just use the .islower() method on the character for that. Regards, Martin From sturlamolden at yahoo.no Fri Mar 3 20:33:31 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 3 Mar 2006 17:33:31 -0800 Subject: Python advocacy in scientific computation In-Reply-To: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> Message-ID: <1141436011.868907.292130@u72g2000cwu.googlegroups.com> Michael Tobis skrev: Being a scientist, I can tell you that your not getting it right. If you speak computer science or business talk no scientist are going to listen. Lets just see how you argue: > These include: source and version control and audit trails for runs, > build system management, test specification, deployment testing (across > multiple platforms), post-processing analysis, run-time and > asynchronous visualization, distributed control and ensemble > management. At this point, no scientist will no longer understand what the heck you are talking about. All have stopped reading and are busy doing experiments in the laboratory instead. Perhaps it sound good to a CS geek, but not to a busy researcher. Typically a scientist need to: 1. do a lot of experiments 2. analyse the data from experiments 3. run a simulation now and then Thus, we need something that is "easy to program" and "runs fast enough" (and by fast enough we usually mean extremely fast). The tools of choice seems to be Fortran for the older professors (you can't teach old dogs new tricks) and MATLAB (perhaps combined with plain C) for the younger ones (that would e.g. be yours truly). Hiring professional programmers are usually futile, as they don't understand the problems we are working with. They can't solve problems they don't understand. What you really ned to address is something very simple: Why is Python better a better Matlab than Matlab? The programs we need to write typically falls into one of three categories: 1. simulations 2. data analysis 3. experiment control and data aquisition (that are words that scientists do know) In addition, there are 10 things you should know about scientific programming: 1. Time is money. Time is the only thing that a scientist cannot afford to lose. Licensing fees for Matlab is not an issue. If we can spend $1,000,000 on specialised equipment we can pay whatever Mathworks or Lahey charges as well. However, time spent programming are an issue. (As are time time spend learning a new language.) 2. We don't need fancy GUIs. GUI coding is a waste of time we don't have. We don't care if Python have fancy GUI frameworks or not. 3. We do need fancy data plotting and graphing. We do need fancy plotting and graphing that are easy to use - as in Matlab or S-PLUS. 4. Anything that has to do with website development or enterprise class production quality control are crap that we don't care about. 5. Versioning control? For each program there is only one developer and a single or a handful users. 6. The prototype is the final version. We are not making software for a living, we are doing research. 7. "My simulation is running to slowly" is the number ONE complaint. Speed of excecution is an issue, regardless of what computer science folks try to tell you. That is why we spend disproportionate amount of time learning to vectorize Matlab code. 8. "My simulation is running of of memory" is the number TWO complaint. Matlab is notoriously known for leaking memory and fragmenting the heap. 9. What are algorithms and data structures? Very few of us knows how to use a datastructure more complicated than an array. That is why we like Matlab and Fortran so much. 10. We are novice programmers. We are not passionate programmers. We take no pride in our work. The easier hack the better. We don't care if we are doing OOP or not. However, we do hate complicated APIs or APIs that look funny. We are used to seeing sin(x) in our calculus textbooks and because of that we don't find Math.Sin(x) particularly elegant -- even though Math.Sin(x) is more OOP and sin(x) clutters the global namespace. Now please go ahead and tell me how Python can help me become a better scientist. And try to steer clear of the computer science buzzwords that don't mean anyting to me. Thanks! Sturla Molden (neuroscience PhD) > The synergies among these programming modes is in some ways harder to > explain than to experience. The Python novice may nevertheless observe > that a single language can take the place of shell scripts, makefiles, > desktop computation environments, compiled languages to build GUIs, and > scripting languages to build web interfaces. In addition, Python is > useful as a wrapper for Fortran modules, facilitating the > implementation of true test-driven design processes in Fortran models. > > Another Python advocacy slogan is "batteries included". The point here > is that (in part because Python is dramatically easier to write than > other languages) there is a very broad range of very powerful standard > libraries that make many tasks which are difficult in other languages > astonishingly easy in Python. For instance, drawing upon the standard > libraries (no additional download required) a portable webserver > (runnable on both Microsoft and Unix-based platforms) can be > implemented in seven lines of code. (See > http://effbot.org/librarybook/simplehttpserver.htm ) Installation of > pure python packages is also very easy, and installation of mixed > language products with a Python component is generally not > significantly harder than a comparable product with no Python > component. > > Among the Python components and Python bindings of special interest to > scientists are the elegant and powerful matplotlib plotting package, > which began by emulating and now surpasses the plotting features of > Matlab, SWIG, which allows for runtime interoperability with various > languages, f2py which specifically interoperates with Fortran, NetCDF > libraries (which cope with NetCDF files with dramatically less fuss > than the standard C or Fortran bindings), statistics packages including > bindings to the R language, linear algebra packages, various > platform-specific and portable GUI libraries, genetic algorithms, > optimization libraries, and bindings for high performance differential > equation solvers (notably, using the Argonne National Laboratory > package PetSC). An especially interesting Python trick for runtime > visualization in models that were not designed to support it, pioneered > by David Beazley's SWILL, embeds a web server in your model code. > > See especially http://starship.python.net/~hinsen/ScientificPython/ and > http://scipy.org as good starting points to learn about scientific uses > of Python. > > mt From sjmachin at lexicon.net Thu Mar 23 21:10:26 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 24 Mar 2006 13:10:26 +1100 Subject: Question about raw string and regex In-Reply-To: <1143164205.830604.151750@u72g2000cwu.googlegroups.com> References: <1143162709.817584.192910@g10g2000cwb.googlegroups.com> <1143164205.830604.151750@u72g2000cwu.googlegroups.com> Message-ID: <44235521@news.eftel.com> On 24/03/2006 12:36 PM, jlowery at blarg.net wrote: > I doubt it, although it might work anyway. You could dispel all doubt in about 15 seconds flat were you to actually try it out. >>> import regex __main__:1: DeprecationWarning: the regex module is deprecated; please use the re module >>> regex.match(r"[ \t]", "\t") -1 >>> regex.match("[ \t]", "\t") 1 >>> import re >>> re.match("[ \t]", "\t") <_sre.SRE_Match object at 0x00AE9058> >>> re.match(r"[ \t]", "\t") <_sre.SRE_Match object at 0x00AE9918> >>> > > Here's another from the same program: > > (a0, b0), (a1, b1), (a2, b2) = classprog.regs[:3] > > Nothing in the Python lib reference on the regs attribute for regex > objects. > Dunno where you're looking, but my Python 1.5.2 has the regex docs, which include a big fat note to the effect of the above DeprecationWarning, plus documentation on the regs attribute. From mensanator at aol.com Fri Mar 24 21:40:20 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 24 Mar 2006 18:40:20 -0800 Subject: a problem to solve In-Reply-To: References: <5oiUf.1818$No6.41433@news.tufts.edu> <1143071664.377833.136660@z34g2000cwc.googlegroups.com> <1143232745.363162.53810@j33g2000cwa.googlegroups.com> <1143237995.862980.135710@i40g2000cwc.googlegroups.com> <1143243662.182759.230130@e56g2000cwe.googlegroups.com> <1143245150.815621.130720@v46g2000cwv.googlegroups.com> Message-ID: <1143254420.545173.129140@z34g2000cwc.googlegroups.com> John Salerno wrote: > mensanator at aol.com wrote: > > >> (homework? a puzzle book?), I am just > >> wondering where the puzzle came from. > > > > The OP mentioned it came from a puzzle game That made me > > think there was likely at least one solution. > > Right, a computer puzzle game (a Myst-style game called Realms of > Illusion), and I know there's at least one answer because it's been > months since I finished the game. :) > > I also think, but can't say for sure, that there is just one solution. _I_ can say for sure, there is just one solution. From mshawjr at frontiernet.net Sun Mar 19 23:22:17 2006 From: mshawjr at frontiernet.net (mshawjr at frontiernet.net) Date: Mon, 20 Mar 2006 04:22:17 GMT Subject: Ink Message-ID: Man I have found this site that has the cheapest ink for any printer. You can compare prices and then review the companies on service and quality. Let me know what you think From fredrik at pythonware.com Sat Mar 25 01:13:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 25 Mar 2006 07:13:57 +0100 Subject: newbie parsing question References: <1143247662.544559.165060@t31g2000cwb.googlegroups.com> Message-ID: "Kun" wrote: > i tried to parse (below) with the regular expression: emails = > re.findall('\S*\s(\w+@\w+\.\w+)', senders) > > and got the following error: > > Traceback (most recent call last): > File "/Life/School/Homework/Spring 2006/OPIM > 399/Tutorial/IMAP/scannermailer.py", line 19, in -toplevel- > emails = re.findall('\S*\s(\w+@\w+\.\w+)', senders) > File > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/sre.py", > line 167, in findall > return _compile(pattern, flags).findall(string) > TypeError: expected string or buffer > > any help would be appreciated. findall expects a string as the target, not a list of strings. you can either use a loop to apply the RE to each string fragment separately, or join the fragments into a single string before you pass it to re.findall. on the other hand, your data looks pretty regular. why not just loop over the fragments and look for things that start with "From:" ? From carsten at uniqsys.com Sun Mar 26 02:04:26 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 26 Mar 2006 02:04:26 -0500 Subject: [ANN] InformixDB-2.2 released Message-ID: <20060326065819.M62918@uniqsys.com> I am pleased to announce a new release of InformixDB, the DB-API 2.0 module for connecting to IBM Informix database engines. Changes since version 2.1: - Support for BOOLEAN columns - DECIMAL and MONEY columns can be fetched as decimal.Decimal instances if the decimal module is available - autocommit mode for connections - Bug fixes: * Output buffer allocation used pointer/int casts that don't work on most 64 bit platforms. * Selecting TEXT/BYTE column from an empty set of rows caused segmentation fault under certain circumstances. * datetime values with trailing double-zeroes were fetched incorrectly. Downloads and info at http://informixdb.sourceforge.net. Best regards, Carsten Haese From fredrik at pythonware.com Wed Mar 8 13:39:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 8 Mar 2006 19:39:40 +0100 Subject: why no block comments in Python? References: <_MCPf.1749$No6.40293@news.tufts.edu> Message-ID: Roy Smith wrote: > > you can quickly comment out regions by putting them > > inside a triple-quoted string.) > > Except that triple-quotes don't nest. ''' """...except when they do""" ''' From cyril.bazin at info.unicaen.fr Mon Mar 6 12:34:46 2006 From: cyril.bazin at info.unicaen.fr (Cyril Bazin) Date: Mon, 6 Mar 2006 18:34:46 +0100 Subject: spliting on ":" In-Reply-To: References: <1141491273.776287.66070@j33g2000cwa.googlegroups.com> Message-ID: On 3/6/06, Bryan Olson wrote: > > Peter Hansen wrote: > > The archives could tell you more, but basically on is usually interested > > in *identity* with a singleton object (None), not in whether the object > > on is examining happens to compare equal. A custom object could be > > designed to compare equal to None in certain cases, even though it *is > > not* None, leading to the "== None" approach being defective code. > > But if a custom class allows instances to compare as equal to None, > we might reasonably expect the programmers had a reason. There's not > much anyone can do with None besides passing it around and comparing > it by value or identity. Insisting on 'is' rather than '==' will break > whatever polymorphism such a custom object was trying to achieve. I agree. None is an object! If you want to compare an object to another object why not using "=="? Cyril -------------- next part -------------- An HTML attachment was scrubbed... URL: From apardon at forel.vub.ac.be Tue Mar 14 08:24:55 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Mar 2006 13:24:55 GMT Subject: Which GUI toolkit is THE best? References: <441172c2$1@news1.ethz.ch> <1142273736.875873.266880@e56g2000cwe.googlegroups.com> <7xy7zenr6u.fsf@ruckus.brouhaha.com> <1142276145.151066.90280@j33g2000cwa.googlegroups.com> Message-ID: Op 2006-03-13, Paul Boddie schreef : > Paul Rubin wrote: >> "Paul Boddie" writes: >> > What people don't usually understand (or rather complain about loudly) >> > is that Trolltech can refuse to license Qt to you under the commercial >> > licence, as is their right as the owner of the copyrighted work. >> >> What is the deal here? Why would they refuse, to someone willing to >> pay the commercial license fee? They are a business, and as such, > > Well, I can't answer for them in any sense (and I should ask you to > substitute any company with a similar business model for Trolltech in > the text, along with accompanying product names, in order to emphasize > the mere speculative nature of my explanation), but all I was trying to > do was to explain the pattern of behaviour that goes something like > this: > > 1. Developer downloads Qt GPL edition. > 2. Developer develops product based on Qt. > 3. Some time later, with finished product, developer now wants > to release a closed source version of the product. > 4. Developer approaches Trolltech and asks for a commercial > licence in order to ship a closed source product. > > Now, since the commercial licence is "per developer", some cunning > outfit could claim that only one developer wrote their product (rather > than one hundred developers, say), but this would be a fairly big > breach of trust (although nothing unusual in the world of commerce, I'm > sure). Would a business making software for other such businesses care > about such things? What kind of recourse would they have? I wonder what this "per developer" means. Suppose ten people are working on a product. But only one person is working on the GUI and comes into contact with the Qt widget. Is that one or ten developers that are counted for the license? -- Antoon Pardon From webraviteja at gmail.com Wed Mar 29 23:19:10 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 29 Mar 2006 20:19:10 -0800 Subject: a hobbyist's dilemma In-Reply-To: References: Message-ID: <1143692350.508279.93500@u72g2000cwu.googlegroups.com> I don't have any dearth of Python needs ( I now, sort of pay my tuition through Python :-) ). But I use it for fun as well, say gaming. For example, I have scripts that send keystrokes based on voice commands or other keystrokes. Having a productive language like Python at your disposal can help automate many of your day to day tasks. http://www.python.org/doc/essays/cp4e.html Besides, it's a lot easier (and fun) to write code for yourself than to make it to distribute to others. From doug.bromley at gmail.com Fri Mar 31 10:43:16 2006 From: doug.bromley at gmail.com (Doug Bromley) Date: Fri, 31 Mar 2006 16:43:16 +0100 Subject: Best IDE for Python? In-Reply-To: References: <1143783179.361616.76750@i39g2000cwa.googlegroups.com> <1143813623.203852.184000@g10g2000cwb.googlegroups.com> <1143816395.190171.298530@t31g2000cwb.googlegroups.com> Message-ID: <288425520603310743q116248a7v624ab40d09773087@mail.gmail.com> You may find the IDE review at Straw Dogs worth a look: http://www.straw-dogs.co.uk/blog/python-ide-review On 3/31/06, Keith B. Perry wrote: > > To me, it just doesn't behave the same way as Eclipse for java. I have > used the plug-in, and I usually use it on my home machine ( I am still a > student). For example, in Java eclipse, if you import a module like math, > then if you want to use a math function, you just type math + period, and > then all the functions pop up in a scroll menu. I love this. I am not > searching through online documentation...etc just to find some stupid > method/function that I know is there. It doesn't seem to behave like this > for Python....I wish it did. > > I still love programming in Python, though. > > > On 3/31/06, Fabio Zadrozny wrote: > > > > > > > > On 31 Mar 2006 06:46:35 -0800, kbperry wrote: > > > > > > I have recently been trying out NewEdit, and it is a pretty good "IDE" > > > for Python. > > > > > > The reason that I have it in quotes is because I haven't really found > > > a > > > true IDE (like the way Eclipse behaves for Java) for python. (I > > > realize that Eclipse has a plug-in for Python, too). > > > > > > So, why wouldn't you consider Pydev (the python plugin for Eclipse) a > > Python IDE? > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From donn at u.washington.edu Tue Mar 7 14:26:39 2006 From: donn at u.washington.edu (Donn Cave) Date: Tue, 07 Mar 2006 11:26:39 -0800 Subject: os.execve(pth,args,env) and os.chroot(pth) = problems References: <1141751079.504570.75980@j52g2000cwj.googlegroups.com> Message-ID: In article <1141751079.504570.75980 at j52g2000cwj.googlegroups.com>, "goodnamesalltaken at gmail.com" wrote: > ... It seems me that the os.chroot() call is messing up the > os.execve() (which executes the cgi script). os.execve(pth, args, > envVariables) is only executed if os.path.exists(pth) returns True. > But when I run a CGI script that os.path.exists(pth) returns True for, > then os.execve(pth) python throws back the error: > > File "/***/***/***/Unpriv.py", line 201, in execCGI > OSError: [Errno 2] No such file or directory > > However I don't see how this is possible if os.path.exists(pth) returns > True, why is it os.execve() has problems finding it. I haven't used chroot enough to know all the pitfalls, but here's one guess: suppose the CGI script file `pth' might actually be a script, with a `#!' top line that points to an interpreter that isn't there, in your chroot space? Donn Cave, donn at u.washington.edu From kent at kentsjohnson.com Sun Mar 5 18:57:07 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sun, 05 Mar 2006 18:57:07 -0500 Subject: Package organization: where to put 'common' modules? In-Reply-To: <1141599776.392714.28350@i39g2000cwa.googlegroups.com> References: <1141419542.750676.176150@z34g2000cwc.googlegroups.com> <44098830$1_3@newspeer2.tds.net> <1141599776.392714.28350@i39g2000cwa.googlegroups.com> Message-ID: <440b7615$1_1@newspeer2.tds.net> fortepianissimo wrote: > Hm this doesn't work. Say I have the following directory structure: > A > |--- util > | |--- foo.py > | > |--- B > |--- bar.py > > And bar.py has this line > > from util import foo > > I then run > > python B/bar.py > > in directory A. Still got error > > ImportError: No module named util Do you have a file util/__init__.py? This is required to make python recognize util as a package. This works for me: C:\WUTemp\A>dir /b/s C:\WUTemp\A\B C:\WUTemp\A\util C:\WUTemp\A\B\bar.py C:\WUTemp\A\B\__init__.py C:\WUTemp\A\util\foo.py C:\WUTemp\A\util\foo.pyc C:\WUTemp\A\util\__init__.py C:\WUTemp\A\util\__init__.pyc C:\WUTemp\A>type util\foo.py def baz(): print 'foo.baz() here' C:\WUTemp\A>type B\bar.py import sys print sys.path from util import foo foo.baz() C:\WUTemp\A>python B\bar.py ['C:\\WUTemp\\A\\B', 'C:\\Python24\\python24.zip', 'C:\\WUTemp\\A', ] foo.baz() here Kent From tomasz.zielonka at gmail.com Fri Mar 17 05:09:31 2006 From: tomasz.zielonka at gmail.com (Tomasz Zielonka) Date: Fri, 17 Mar 2006 10:09:31 +0000 (UTC) Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <8764medlhm.fsf@qrnik.zagroda> <1142556358.098924.59180@e56g2000cwe.googlegroups.com> <1142559980.525680.282250@u72g2000cwu.googlegroups.com> Message-ID: Dan Piponi wrote: > Is this Haskell implementation what you want? It does the wildcard > matching through a state machine and it essentially threads the > state machine through the cartesian product, switching to the > ordinary cartesian product when possible as an optimisation. > The execution of the state machine is shared by strings with the > same prefix making it reasonably efficient even though the state > machine itself isn't optimised. I've implemented the same concept yesterday evening: ----8<--------8<--------8<--------8<--------8<--------8<--------8<--------8<---- module WildCartesian where import List data Pat a = All | Lit a deriving (Show, Eq) advancePattern :: Eq a => a -> [Pat a] -> [[Pat a]] advancePattern y (Lit x : ps) | x == y = [ps] | otherwise = [] advancePattern y (All : ps) = [All : ps] ++ [ps] ++ advancePattern y ps advancePattern _ [] = [] generateNotMatching :: Eq a => [a] -> Int -> [[Pat a]] -> [[a]] generateNotMatching alphabet = gen [] where gen _ n pats | any (\ps -> all (== All) ps && (not (null ps) || n == 0)) pats = [] gen acc 0 _ = [reverse acc] gen acc n pats = [ w | x <- alphabet , let pats' = [ p' | p <- pats, p' <- advancePattern x p ] , w <- gen (x : acc) (n - 1) pats' ] test :: IO () test = do t [1,2] 3 [[Lit 1, All, Lit 2]] t ['a','b'] 3 [[Lit 'a', All, Lit 'b'], [Lit 'b', All, Lit 'a']] t [1,2] 3 [[Lit 1, All, Lit 2], [Lit 2, All, Lit 1]] where t a b c = do putStrLn (concat (intersperse " " ["generateNotMatching", show a, show b, show c])) mapM_ (putStrLn . (" "++) . show) (generateNotMatching a b c) ----8<--------8<--------8<--------8<--------8<--------8<--------8<--------8<---- Best regards Tomasz -- I am searching for programmers who are good at least in (Haskell || ML) && (Linux || FreeBSD || math) for work in Warsaw, Poland From TheExpert at ExpertHumor.com Thu Mar 30 23:03:55 2006 From: TheExpert at ExpertHumor.com (Expert Humor) Date: 31 Mar 2006 04:03:55 GMT Subject: Illegal Immigration, the Non-Issue of the Week?????????????? Message-ID: <719706633006@free.teranews.com> The way our politicians rushed to talk about illegal immigration this week, maybe they thought it came with a free lunch. They won't do anything about it, but it will get them some money. The Expert provides the details at: http://www.ExpertHumor.com/ *** Free account sponsored by SecureIX.com *** *** Encrypt your Internet usage with a free VPN account from http://www.SecureIX.com *** From zhan0645 at yahoo.com Tue Mar 28 19:38:36 2006 From: zhan0645 at yahoo.com (Yanping Zhang) Date: Tue, 28 Mar 2006 16:38:36 -0800 (PST) Subject: python ctype question about "access violation reading location 0x5a5a5a5a" Message-ID: <20060329003836.88170.qmail@web52911.mail.yahoo.com> Hi All, I need to use this C routine in python and there is a void pointer parameter in it: (this routine was written by someone else): myfunc(int a, (void *)userdata, bool b) I saw someone in his C++ wrapper used this routine in this way: myfunc(a, (void *)0x5a5a5a5a, b) In my python wrapper, I tried to call it as the following and both failed: 1. myfunc(c_int(a), 0x5a5a5a5a, c_int(b)) got error "access voilation reading from 0x5a5a5a5a" 2. data = 0x5a5a5a5a mydata = c_void_p(data) myfunc(c_int(a), mydata, c_int(b)) same error as in 1 Can anyone know how to fix it? Thanks! __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From martin at v.loewis.de Sun Mar 19 07:41:37 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 19 Mar 2006 13:41:37 +0100 Subject: Getting .NET SDK to work with Python 2.4.2 In-Reply-To: <1142721716.734835.157980@z34g2000cwc.googlegroups.com> References: <1142721716.734835.157980@z34g2000cwc.googlegroups.com> Message-ID: <441D5181.2060103@v.loewis.de> Dave wrote: > So i go to the cmd and go to the directory and type > "python setup.py build" (Will have to install after) and it comes up > with this(after everything else runs smoothly): > running build_ext > error: The .NET SDK needs to be installed before building extensions > for python. The error message is misleading. It is not the SDK that you need, but Visual Studio 7.1. Alternatively, you can try building the extension with the GNU mingw32 compiler. Regards, Martin From ziga.seilnacht at gmail.com Fri Mar 24 12:26:22 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 24 Mar 2006 09:26:22 -0800 Subject: property docstrings References: Message-ID: <1143221181.873321.174770@i40g2000cwc.googlegroups.com> Darren Dale wrote: > I am trying to work with properties, using python 2.4.2. I can't get the > docstrings to work, can someone suggest what I'm doing wrong? I think the > following script should print "This is the doc string.", but instead it > prints: > > "float(x) -> floating point number > > Convert a string or number to a floating point number, if possible." > > Thanks, > Darren > a=Example() > print 'myattr docstring:\n', a.myattr.__doc__ > print 'foo docstring:\n', a.foo.__doc__ > print 'bar docstring:\n', a.bar.__doc__ change this part to: print 'myattr docstring:\n', Example.myattr.__doc__ print 'foo docstring:\n', Example.foo.__doc__ print 'bar docstring:\n', Example.bar.__doc__ What happens is that when property is accessed from an instance, it returns whatever the fget function returns, and the __doc__ attribute is then looked up on that object. To get to the actual property object (and its __doc__ attribute) you have to access it from a class. Ziga From bdesth.quelquechose at free.quelquepart.fr Thu Mar 9 20:34:03 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 10 Mar 2006 02:34:03 +0100 Subject: Any python HTML generator libs? In-Reply-To: <1141936438.584242.129220@z34g2000cwc.googlegroups.com> References: <1141936438.584242.129220@z34g2000cwc.googlegroups.com> Message-ID: <4410abea$0$8498$626a54ce@news.free.fr> Sullivan WxPyQtKinter a ?crit : > Hi, everyone. Simply put, what I need most now is a python lib to > generate simple HTML. > > I am now using XML to store my lab report records. I found python > really convinient to manipulate XML, so I want to make a small on-line > CGI program to help my colleagues to build their lab report records > into XML, for storage, HTML display (for others to browse) and search. > > With python's standard lib, the DOM object could realize the XML > storage and search quite easily, but for HTML generation, it is a > great headache. You may want to have a look at Kid: http://kid.lesscode.org/trac/wiki/SimpleXmlDocumentProcessingRecipe From andre.roberge at gmail.com Thu Mar 9 12:34:03 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 9 Mar 2006 09:34:03 -0800 Subject: implementation of "complex" type In-Reply-To: <1141924817.076466.23680@v46g2000cwv.googlegroups.com> References: <1141895757.128437.159460@i39g2000cwa.googlegroups.com> <1141924817.076466.23680@v46g2000cwv.googlegroups.com> Message-ID: <1141925642.987617.237910@i40g2000cwc.googlegroups.com> Russ wrote: > "Why don't you show us your complex class?" > > Because I don't have a complex class. I merely used the complex class > as an example to test the referencing behavior. Please read more > carefully next time. I'm not the one you were replying to, but I would say to you... "Please write more carefully next time". You wrote: >But when I tried the same thing with my own class in place of >"complex" above, I found that both x and y were doubled. Why don't you show us your own whatever_it_is_named_except_it_is_not_complex class? When you are the one seeking help, you may find it helpful to be polite.... I have found that comp.lang.python has some of the most friendly and helpful people around. They will undoubtably help you (as they helped me many times), if you provide answers to the questions they ask in trying to help you... Andr? From tkpmep at hotmail.com Wed Mar 22 17:01:08 2006 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 22 Mar 2006 14:01:08 -0800 Subject: Using PyExcelerator Message-ID: <1143064868.198835.45150@u72g2000cwu.googlegroups.com> I have just installed PyExcelerator, and now want to use it to read Excel spreadsheets with a variable number of rows and columns and with multiple sheets. Unfortunately, no documentation seems to accompany PyExcelerator. Does anyone know of a good source of documentations and/or examples? The author provides some examples, but these tend to involve writing data into spreadsheets one cell at a time. Thanks in advance Thomas Philips From cito at online.de Tue Mar 21 04:29:16 2006 From: cito at online.de (Christoph Zwerschke) Date: Tue, 21 Mar 2006 10:29:16 +0100 Subject: ** Operator In-Reply-To: References: <1142833145.976550.104830@v46g2000cwv.googlegroups.com> <1142833540.860154.137040@u72g2000cwu.googlegroups.com> <1hcgw5p.1ufznwe1lxeagfN%aleaxit@yahoo.com> Message-ID: Ron Adam wrote: > I agree and think the "for language lawyers" should be changed to > something that encourages people to read it instead of encouraging them > to avoid it. Maybe: > > "The Python language structure for everyone". > > If it's hard to read and understand, then that can and should be fixed. Hm, actually that was not my point. I think the writers of the Language Reference already did a very good job. The precise and "authoritative" language reference covering all the subtleties and special cases will never be fun to read. You would rather learn the use of the keywords and the basic rules and magic attributes of the language from a good tutorial or handbook, and look up the Language Reference really seldomly. You can program quite well in Python without ever having looked into the official Language Reference. Newbies should not think they need to read it in order to start programming. However, it is different with the Lib Reference. This is used on a daily basis, you will often look into it, Python users are accustomed to it, and it should invite readers to really browse and read and learn more about the power of the batteries included. My point was that since users are more accustomed to and prefer to use the Lib reference as their first source of information rather than the Language reference, it should not be reluctant to mention some things which strictly speaking belong to the Language Reference. In some cases, it can also point to the Lanugage Reference for the details (and it does so already). -- Christoph From gandalf at designaproduct.biz Tue Mar 7 14:44:15 2006 From: gandalf at designaproduct.biz (Laszlo Zsolt Nagy) Date: Tue, 07 Mar 2006 20:44:15 +0100 Subject: Send email notification In-Reply-To: <1141759889.952367.59260@j33g2000cwa.googlegroups.com> References: <1141759889.952367.59260@j33g2000cwa.googlegroups.com> Message-ID: <440DE28F.2090503@designaproduct.biz> Ernesto wrote: >Is there a special module for mail ? > >I'd like to send an email [to 'n' unique email addresses] from a python >script. > > http://www.justfuckinggoogleit.com/search.pl?python+smtp From sturlamolden at yahoo.no Sun Mar 5 15:18:12 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 5 Mar 2006 12:18:12 -0800 Subject: Python advocacy in scientific computation In-Reply-To: References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> <1141583453.403143.189400@i40g2000cwc.googlegroups.com> Message-ID: <1141589892.094037.18410@i40g2000cwc.googlegroups.com> Robert Kern wrote: > And you need to ask why Python is a better Matlab than Matlab? First there are a few things I don't like: 1. Intendation as a part of the syntax, really annoying. 2. The "self.something" syntax is really tedious (look to ruby)! 4. Multithreading and parallel execution is impossible AFAIK because of the so-called GIL (global interpreter lock). Matlab is perhaps even worse in this respect. 5. I don't like numpy's array slicing. Array operations should be a part of the language, as in Matlab, Fortran 90, Ada 95, D, Octave. And there is a couple of questions I need answered: 1. Can python do "pass by reference"? Are datastructures represented by references as in Java (I don't know yet). 2. How good is matplotlib/pylab? I tried to install it but only get error messages so I haven't tested it. But plotting capabilities is really major issue. 3. Speed. I haven't seen any performance benchmarks that actually deals with things that are important for scientific programs. 4. Are there "easy to use" libraries containing other stuff important for scientific programs, e.q. linear algebra (LU, SVD, Cholesky), Fourier transforms, etc. E.g. in Matlab I can just type, [u,s,v] = svd(x) % which calls LAPACK linked to ATLAS or vendor-optimized BLAS Even though the language itself is very limited this type of library functionality more than makes up for it. I have looked for alternatives to Matlab for quite a while, mainly due to the cost, the ?poor speed and poor memory management. I am not sure it is Python but so far I have not found anything mor promising either. From bdesth.quelquechose at free.quelquepart.fr Sun Mar 26 18:34:14 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 27 Mar 2006 01:34:14 +0200 Subject: Python types In-Reply-To: <1143306481.966061.26300@t31g2000cwb.googlegroups.com> References: <1143230541.717833.35440@e56g2000cwe.googlegroups.com> <44247674$0$25385$636a55ce@news.free.fr> <1143306481.966061.26300@t31g2000cwb.googlegroups.com> Message-ID: <4426f7a4$0$27969$626a54ce@news.free.fr> Salvatore a ?crit : > Thank's everybody :-) > > > Here is a type d?finition I've found on the net which I agree with : > > Attribute of a variable which determines the set of the values this > variabe can take and the > operations we can apply on it. Then - as already pointed by Alex - there is no type in Python, since there is no variable (even if this term is often improperly used for bindings) !-) Ok, let's s/variable/object/g and define some objects and operations: def myop(obj): return obj.foo * 2 class Bar(object): pass b = Bar() Can we apply the myop() operation on the object name 'b' is bound to ? myop(b) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in myop AttributeError: 'Bar' object has no attribute 'foo' Well... but wait a minute: b.foo = [] myop(b) -> [] Err... Wait another minute: b2 = Bar() type(b) is type(b2) -> True myop(b2) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in myop AttributeError: 'Bar' object has no attribute 'foo' Ok, so even if Python itself declares b and b2 (read: objects that names b and b2 are bound to) to be of the same type, you cannot apply the myop() operation on b2... Also: del b.foo myop(b) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in myop AttributeError: 'Bar' object has no attribute 'foo' So *sometimes* you can apply myop() to b, and sometimes you can't. Now if we come back to your original post: """ All objects seem to have a perfectly defined type """ "Perfectly defined" ? Really ? Not for your current definition of 'type' at least !-) I still mostly agree with the given definition of type. But the fact is that in Python, the type*s* of an object are not so perfectly defined - they're mostly implicits, and can vary during the object's lifetime. Note that it does'nt make Python weakly typed - you cannot perform any arbitrary operation on a given object, only the operations this object can support at a given moment. FWIW, if you want a weakly typed language, take a look at C. From deets at nospam.web.de Wed Mar 29 11:56:23 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 29 Mar 2006 18:56:23 +0200 Subject: Terminating a subprocess question References: <1143649900.667952.15410@t31g2000cwb.googlegroups.com> Message-ID: <48vsl1Fmc3tkU1@uni-berlin.de> Ernesto wrote: > I'm opening a telnet session with the subprocess call below. I then > wait ten seconds and attempt to terminate the telnet window I created. > Unfortuantely, the telnet window remains after the 'TerminateProcess" > call below. This software works great for opening an executable > directly (i.e. Handle = subprocess.Popen("myProgram.exe), but here I'm > using the Windows 'start' command inside, which I think has an effect. > > > Is there another way I can force termination of the telnet session I > create ? Maybe using the module telnetlib instead? Diez From jaywgraves at gmail.com Tue Mar 21 16:48:17 2006 From: jaywgraves at gmail.com (jay graves) Date: 21 Mar 2006 13:48:17 -0800 Subject: NOT Python: Taxonomy list reference References: <44206b1f$1@nntp.zianet.com> Message-ID: <1142977697.816897.256020@v46g2000cwv.googlegroups.com> ej wrote: > Any Pythonistas out there know the list I am referring to and could point me > to it? Thanks for your time! :) google for "Celestial Emporium of Benevolent Knowledge" I don't have my copy with me now but I think I might have seen it in "Code Complete 2" or maybe I'm just imagining that. Also Mark Pilgrim's diveintomark.org blog (http://diveintomark.org/archives/rooms/) has categories that are reminiscent of the list. I think this was my first exposure to it. HTH. ... jay graves From onurb at xiludom.gro Tue Mar 21 06:06:12 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 21 Mar 2006 12:06:12 +0100 Subject: [CODE] - Python Newcomer Starting with Coding In-Reply-To: References: Message-ID: <441fde5d$0$29689$636a55ce@news.free.fr> Ilias Lazaridis wrote: > Where can I find practical coding examples for real life coding problems? Probably in real life code ?-) > Something like a categorized solution guide? Look for the Python cookbook (google is your friend). > - > > My current problem: > > * create a folder > * seems to be: os.mkdir(path) I wouldn't even count this as a coding problem, except perhaps for a total CS newbie. > * obtain the path of a python package import package print package.__file__ > * copy the content of the package folder to the created folder import shutil help(shutil.copytree) (snip) > I've looked in the Python 2.4 documentation, but the resulting > possibilities are too much. ??? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From Serge.Orlov at gmail.com Sat Mar 18 00:16:59 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 17 Mar 2006 21:16:59 -0800 Subject: Python vs. Java gzip performance References: <1142610889.512781.69650@j33g2000cwa.googlegroups.com> Message-ID: <1142659018.979805.121760@u72g2000cwu.googlegroups.com> Bill wrote: > Is there something that can be improved in the Python version? Seems like GzipFile.readlines is not optimized, file.readline works better: C:\py>python -c "file('tmp.txt', 'w').writelines('%d This is a test\n' % n for n in range(10000))" C:\py>python -m timeit "open('tmp.txt').readlines()" 100 loops, best of 3: 2.72 msec per loop C:\py>python -m timeit "open('tmp.txt').readlines(1000000)" 100 loops, best of 3: 2.74 msec per loop C:\py>python -m timeit "open('tmp.txt').read().splitlines(True)" 100 loops, best of 3: 2.79 msec per loop Workaround has been posted already. -- Serge. From frithiof.jensen at die_spammer_die.ericsson.com Fri Mar 17 04:36:45 2006 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Fri, 17 Mar 2006 10:36:45 +0100 Subject: comparing huge files References: <1142475204.998414.213520@j52g2000cwj.googlegroups.com> <1142505157.496128.148740@e56g2000cwe.googlegroups.com> Message-ID: wrote in message news:1142505157.496128.148740 at e56g2000cwe.googlegroups.com... > thanks for the reply, > I have used another method to solve my problem. ie > 1) get the total count of the first file > 2) write this total count to basecnt eg basecnt > 3) get another file, get the total count of this file. eg filecnt > 4) if filecnt > basecnt, read in the values from file[basecnt:filecnt] > 5) if filecnt < basecnt, overwrite original basecnt and start over > again. > > basically, the problem domain is i want to get the most current records > from a log file to review after every 3 hours. so this log file will > increase or accumulate. > I did this: fp = os.popen('/usr/sbin/logtail /var/log/syslog') loglines = fp.readlines() .... pyparsing ... stuff .... from loglines ;-) Python is maybe overkill too - have "cron" call "logtail" and pibe the output whereever? PS: "logtail" is very simple, it works simply by maintaining a "bookmark" from the last read that is updated after each time the file is read (i.e. on each call). It is probably a very easy thing to implement in Python. On Linux/UNIX syslog+logutils can do a lot of work just by configuration (but you did not say you are on unix) From amaltasb at gmail.com Fri Mar 31 23:37:06 2006 From: amaltasb at gmail.com (amaltasb at gmail.com) Date: 31 Mar 2006 20:37:06 -0800 Subject: Pickle or Mysql In-Reply-To: <7xhd5drk2d.fsf@ruckus.brouhaha.com> References: <1143864315.283697.20970@v46g2000cwv.googlegroups.com> <7xhd5drk2d.fsf@ruckus.brouhaha.com> Message-ID: <1143866226.807178.239190@z34g2000cwc.googlegroups.com> So, Is Shelve a perfect solution (besides Mysql), to store large key/value pairs, and which are updated frequently by multiple clients. Thanks Paul Rubin wrote: > amaltasb at gmail.com writes: > > Can I use Pickle to store about 500,000 key value pairs.. or should I > > use mySql. Which one is best for performance, as the key value pair > > increases. > > That's an awfully large pickle. Maybe you want shelve. If there > are frequent updates, multiple clients, etc., then yes, use a database > like mysql. From steve at REMOVETHIScyber.com.au Fri Mar 3 23:41:53 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 04 Mar 2006 15:41:53 +1100 Subject: How to except the unexpected? References: Message-ID: On Sat, 04 Mar 2006 00:10:17 +0100, Rene Pijlman wrote: > I've writen an application that uses urllib2, urlparse, robotparser and > some other modules in the battery pack. One day my app failed with an > urllib2.HTTPError. So I catch that. But then I get a urllib2.URLError, so > I catch that too. The next day, it encounters a urllib2.HTTPError, then a > IOError, a socket.timeout, httplib.InvalidURL,... > > How do you program robustly with these modules throwing all those > different (and sometimes undocumented) exceptions at you? How robust do you want to be? Do you want to take a leaf out of Firefox and Windows XP by generating an error report and transmitting it back to the program maintainer? > A catchall seems like a bad idea, since it also catches AttributeErrors > and other bugs in the program. ExpectedErrors = (URLError, IOError) ErrorsThatCantHappen = (LookupError, ArithmeticError, AssertionError) try: process_things() except ExpectedErrors: recover_from_error_gracefully() except ErrorsThatCantHappen: print "Congratulations! You have found a program bug!" print "For a $327.68 reward, please send the following " \ "traceback to Professor Donald Knuth." raise except: print "An unexpected error occurred." print "This probably means the Internet is broken." print "If the bug still occurs after fixing the Internet, " \ "it may be a program bug." log_error() sys.exit() -- Steven. From fredrik at pythonware.com Tue Mar 7 02:07:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 7 Mar 2006 08:07:58 +0100 Subject: figuring out how much data was sent so far via XML-RPC? References: <1eb708be0603061722y7f751902ha1216f7636f16425@mail.gmail.com> Message-ID: Ratko Jagodic wrote: > I am currently using XML-RPC for a very convenient quick-and-dirty way of > sending some files (base64 encoded). > The files can be bigger sometimes (10-20mb) and I was wondering if there is > a way to see how much data was sent already and how much still needs to be > sent (like a progress bar). some "monkey overriding" might help: # start import xmlrpclib class MyConnection: def __init__(self, conn): self.conn = conn def send(self, data): # split send up in pieces for i in range(0, len(data), 100): print "(%d of %d)" % (i, len(data)), self.conn.send(data[i:i+100]) print def __getattr__(self, key): # delegate everything else return getattr(self.conn, key) class MyTransport(xmlrpclib.Transport): def make_connection(self, host): conn = xmlrpclib.Transport.make_connection(self, host) return MyConnection(conn) server = xmlrpclib.ServerProxy( "http://effbot.org/rpc/echo.cgi", transport=MyTransport() ) x = server.echo(10000*"*") print type(x), len(x) # this prints # (0 of 10148) (100 of 10148) (200 of 10148) ... /snip/ # 10000 From preved.rly at gmail.com Thu Mar 30 09:30:52 2006 From: preved.rly at gmail.com (preved.rly at gmail.com) Date: 30 Mar 2006 06:30:52 -0800 Subject: Countdown from 2 minutes - how? References: <1143725108.307128.16110@v46g2000cwv.googlegroups.com> Message-ID: <1143729052.584614.289050@v46g2000cwv.googlegroups.com> #!/bin/env python # countdown.py import time import doctest def countdown( time_in_minutes): """ >>> import countdown >>> countdown.countdown(0.1) # doctest:+ELLIPSIS 6 5 ... 1 Time is up """ for i in reversed(xrange(1, int(time_in_minutes * 60) + 1)): print i time.sleep(1) print 'Time is up' if __name__=='__main__': doctest.testmod() From grflanagan at yahoo.co.uk Thu Mar 2 11:48:10 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 2 Mar 2006 08:48:10 -0800 Subject: setattr question Message-ID: <1141318090.569997.247760@z34g2000cwc.googlegroups.com> Hello I have the following code: #### builder.py ######### class HtmlBuilder(object): @staticmethod def page(title=''): return HtmlPage(title) @staticmethod def element(tag, text=None, **attribs): return HtmlElement(tag, text, **attribs) @staticmethod def literal(text): return HtmlLiteral(text) class HtmlElementFactory(object): def __init__(self): for tag in ['li', 'ul']: setattr( self, tag, HtmlBuilder.element(tag) ) ######################### and so I can do the following: html = HtmlElementFactory() ul = html.ul ul.attrib['class'] = 'default' for i in range(3): li = html.li li.text = 'ghfhj' ul.append(li) print ul.to_string() but what I'd like to do is: html = HtmlElementFactory() ul = html.ul( class='default' ) for i in range(3): ul.append( html.li( 'ghfhj' ) print ul.to_string() ie. to pass along *args and **kwargs to the HtmlElement constructor. Any suggestions? Or is there a better way to this kind of thing? thanks Gerard From rvernica at ics.uci.edu Mon Mar 6 01:31:41 2006 From: rvernica at ics.uci.edu (Rares Vernica) Date: Sun, 05 Mar 2006 22:31:41 -0800 Subject: re.search Message-ID: <440BD74D.8080002@ics.uci.edu> Hi, Isn't the following code supposed to return ('1994')? >>> re.search('(\d{4})?', '4 1994').groups() (None,) Thanks, Ray From peter_cole at comcast.net Wed Mar 22 13:21:13 2006 From: peter_cole at comcast.net (Peter Cole) Date: Wed, 22 Mar 2006 13:21:13 -0500 Subject: Trouble with generator as method Message-ID: I'm having difficulty understanding why this doesn't work: import sys, new, inspect class T: def foo(self): yield 1 yield 2 yield 3 t = T() ic = t.__class__ for key in ic.__dict__.keys(): if inspect.isfunction(ic.__dict__[key]): im = new.instancemethod(ic.__dict__[key], t, ic) print t.foo print im print 't.foo().next() = %s' % t.foo().next() print 'im.next() = %s' % im.next() >>> ================================ RESTART ============== >>> > > t.foo().next() = 1 Traceback (most recent call last): File "D:/python242/Test Scripts/trial.py", line 22, in -toplevel- print 'im.next() = %s' % im.next() AttributeError: 'function' object has no attribute 'next' >>> From siona at chiark.greenend.org.uk Thu Mar 23 08:52:03 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 23 Mar 2006 13:52:03 +0000 (GMT) Subject: Can XML-RPC performance be improved? References: <48apnrFj7ambU1@uni-berlin.de> Message-ID: wrote: > Diez> Sion Arrowsmith wrote: > >> I've got an established client-server application here where there > >> is now a need to shovel huge amounts of data (structured as lists of > >> lists) between the two, and the performance bottleneck has become > >> the amount of time spent parsing XML ... > Diez> CORBA. Or TCP/IP directly. I know that isn't really the answer > Diez> you're looking for - but there is an overhead parsing XML, and > Diez> that can't go away. >Ah, but if both ends of the pipe happen to be running Python, you can >cheat. ;-) Run your list through marshal.dumps() before passing it to >xmlrpclib, then undo the marshalling on the other end. > [ ... ] >If you can swing it, I'd be willing to bet you a beer your XML parsing time >will all but disappear. I wouldn't take you up on that bet, because I'd already considered that as a likely solution, and while I was asking here another member of the team went away and implemented it for me. Except with cPickle (as suggested elsewhere in the thread) -- we've got DateTime objects in there, which marshal chokes on. Initial tests show you'd've comfortably won your beer: 16s XML parsing down to 0.5s parsing plus 1.5s unpickling. >If you're not using xmlrpclib with some sort of C helper (like sgmlop), try >that as well. Big difference parsing XML in C and Python. Diez edited out the bit where I said we were using sgmlop and worried about what it would be like if we weren't 8-) -- \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 scott.catalina.ctr at scott.af.mil Wed Mar 8 11:21:05 2006 From: scott.catalina.ctr at scott.af.mil (Catalina Scott A Contr AFCA/EVEO) Date: Wed, 8 Mar 2006 10:21:05 -0600 Subject: help with loops Message-ID: <56BF0C633F594948B90E97636666DDF7A66356@AMCW3VN503.amc.ds.af.mil> Paul, I will check out difflib thanks. Scott -------------- next part -------------- An HTML attachment was scrubbed... URL: From pydecker at gmail.com Sun Mar 5 19:37:46 2006 From: pydecker at gmail.com (Peter Decker) Date: Sun, 5 Mar 2006 19:37:46 -0500 Subject: Write a GUI for a python script? In-Reply-To: References: <1141377383.013956.44090@j33g2000cwa.googlegroups.com> Message-ID: On 3/5/06, Bill Maxwell wrote: > Thanks for the info. Knowing that, I was able to create a simple app in > the Dabo Designer that contains a Notebook. > > But, I'm having a heck of a time finding any documentation at all on > Dabo. I looked all thru the website(s), and have combed the Dabo > software package itself. > > Either I'm doing something wrong, or documentation is pretty sparse for > Dabo. No, you're not doing anything wrong. There isn't a whole lot of documentation. That's one of the problems with projects being actively developed: the developers are too busy with the development work to step back and write the docs. They have asked for people to help out if they can (it is open source, after all), but there hasn't been a whole lot of that yet. I think a lot of people are like me: they have figured out enough to make it work, and are doing some great stuff with it, but don't feel that they know it enough to document it. > What little info I could find on the Dabo Wiki seems pretty old. I also > watched the two Sizer videos, but there's not enough info there to learn > much. I have to agree. The videos are great, but so much more is needed. One thing I can suggest is to post any questions on the dabo-users list. Both the authors are very responsive and helpful. > I read somewhere that they are concentrating on the User Interface > designer instead of the database aspects. The GUI maker is what I'm > interested in using, not the rest. I don't want to code the GUI > manually. Do you know where I can find more information on the > Designer? I think that the database side of things has been done for over a year, and now they're looking to add support for more database types as people start using it with other stuff. But as far as the GUI Designer goes, I'd post questions on the dabo-users list. -- # p.d. From spamspam at spam.eggs Sat Mar 11 18:26:54 2006 From: spamspam at spam.eggs (Ben C) Date: 11 Mar 2006 23:26:54 GMT Subject: Dictionary project References: <00ad01c64553$93d01e90$6400a8c0@D1FWTS61> Message-ID: On 2006-03-11, Michael Spencer wrote: > brandon.mcginty at gmail.com wrote: >> Hi All, >> First, I hope this post isn't against list rules; if so, I'll take note in >> the future. >> >> I'm working on a project for school (it's not homework; just for fun). >> For it, I need to make a list of words, starting with 1 character in length, >> up to 15 or so. >> It would look like: >> >> A B C d E F G ... Z Aa Ab Ac Ad Ae Aaa Aab Aac This is really "permutations" you're trying to work out I think. Python generators are quite good for this kind of thing. This works, but isn't especially pretty: import string def letters(): while 1: for char in string.lowercase: yield char yield None def count(n): digits = [letters() for i in range(n)] s = [d.next() for d in digits] def output(): print string.join(reversed(s), "") output() while 1: i = 0 while 1: s[i] = digits[i].next() if s[i] is not None: break s[i] = digits[i].next() i += 1 if i == n: return output() count(3) Obviously you can call count with any number, and if you just change letters() to yield members of some other set you can make permutations of different things. I think 15 is going to give you rather a lot of permutations though. 1677259342285725925376 to be precise. You might have to wait a rather long time. From hancock at anansispaceworks.com Fri Mar 10 22:06:27 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 10 Mar 2006 21:06:27 -0600 Subject: Speed of data structures in python In-Reply-To: References: Message-ID: <20060310210627.52d0ca44@samwise.anansi> On Sat, 11 Mar 2006 13:12:30 +1100 "Steven D'Aprano" wrote: > On Fri, 10 Mar 2006 23:24:46 +1100, Dave wrote: > > Hi. I am learning PyOpenGL and I am working with a > > largish fixed scene composed of several thousand > > GLtriangles. I plan to store the coords and normals in > > a NumPy array. > > > > Is this the fastest solution in python? > Optimization without measurement is at best a waste of > time and at worst counter-productive. Why don't you time > your code and see if it is fast enough? > > See the timeit module, and the profiler. Talk about knee-jerk reactions. ;-) It's a *3D animation* module -- of course it's going to be time-critical. Sheesh. Now *that* is stating the obvious. The obvious solution is actually a list of tuples. But it's very possible that that won't be fast enough, so the NumPy approach may be a significant speedup. I doubt you need more than that, though. I think the real question is not going to be how fast your code handles data, though, but rather how fast you can get that data into PyOpenGL and back. So the real fastest format is going to be "whatever PyOpenGL uses" -- so I'd look that up. For comparison, SDL uses "surfaces" to store 2D data, so when programming in PyGame, your first step is to load every image into a surface. Once there, display to the screen is very very fast -- but moving from image to surface is typically slow, no matter how spiffy your image format may be internally. I suspect something similar applies to PyOpenGL. -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From iker.arizmendi at gmail.com Tue Mar 7 11:09:24 2006 From: iker.arizmendi at gmail.com (iker.arizmendi at gmail.com) Date: 7 Mar 2006 08:09:24 -0800 Subject: popen and exit code on Windows References: <1141673931.111985.166520@i40g2000cwc.googlegroups.com> Message-ID: <1141747764.627437.170800@j52g2000cwj.googlegroups.com> Thanks for the reply Giovanni. Is this behaviour of the close method on Windows documented anywhere? Regards, Iker From ziga.seilnacht at gmail.com Tue Mar 21 11:13:05 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 21 Mar 2006 08:13:05 -0800 Subject: user-supplied locals dict for function execution? References: <1142875454.906993.126370@v46g2000cwv.googlegroups.com> <441eedbd$0$20865$636a55ce@news.free.fr> <1142879594.924929.96440@v46g2000cwv.googlegroups.com> <441f0623$0$23127$626a54ce@news.free.fr> <1142887575.402624.156050@e56g2000cwe.googlegroups.com> Message-ID: <1142957585.007056.276090@t31g2000cwb.googlegroups.com> Lonnie Princehouse wrote: > Occaisionally, the first two lines of The Zen of Python conflict with > one another. > > An API I'm working on involves a custom namespace implementation using > dictionaries, and I want a pretty syntax for initializing the custom > namespaces. The fact that these namespaces are implemented as > dictionaries is an implementation detail, and I don't want the users to > access them directly. I find the "implicit update" syntax to be much > cleaner: > This can be easier achieved with a custom metaclass: >>> class MetaNamespace(type): ... def __new__(metaclass, name, bases, dict): ... try: ... Namespace ... except NameError: ... return type.__new__(metaclass, name, bases, dict) ... dict.pop('__module__', None) ... return dict ... >>> class Namespace(object): ... __metaclass__ = MetaNamespace ... Now whenever you want to create your dictionary you simply declare a class that inherits from Namespace: >>> class MyNamespace(Namespace): ... x = 5 ... y = 'spam' ... z = 'eggs' ... >>> print sorted(MyNamespace.items()) [('x', 5), ('y', 'spam'), ('z', 'eggs')] Ziga From mtobis at gmail.com Mon Mar 20 15:38:55 2006 From: mtobis at gmail.com (Michael Tobis) Date: 20 Mar 2006 12:38:55 -0800 Subject: can't rebind magic methods In-Reply-To: <1hceppf.1smucdv4fkudsN%aleaxit@yahoo.com> References: <1142727958.529520.302980@j33g2000cwa.googlegroups.com> <1hceppf.1smucdv4fkudsN%aleaxit@yahoo.com> Message-ID: <1142887135.270380.123040@g10g2000cwb.googlegroups.com> Thanks! Only a minor correction: the last line should be _setdelegate(myint, int,'__%s__' % spec) The business with f.func_name struck me as unnecessary, but I was quite wrong. This was an interesting exercise for me. Thanks. Michael From mahs at telcopartners.com Wed Mar 22 14:57:31 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Wed, 22 Mar 2006 11:57:31 -0800 Subject: Per instance descriptors ? In-Reply-To: <44216fc5$0$26190$626a54ce@news.free.fr> References: <44211ee8$0$7890$636a55ce@news.free.fr> <1143038744.159609.104460@g10g2000cwb.googlegroups.com> <44216fc5$0$26190$626a54ce@news.free.fr> Message-ID: bruno at modulix wrote: > Ziga Seilnacht wrote: >> bruno at modulix wrote: >> >>> Hi >>> >>> I'm currently playing with some (possibly weird...) code, and I'd have a >>> use for per-instance descriptors, ie (dummy code): >> >> >> >>> Now the question: is there any obvious (or non-obvious) drawback with >>> this approach ? >> ... > >> ... def __getattribute__(self, name): >> ... v = object.__getattribute__(self, name) >> ... if not isinstance(v, types.FunctionType) \ > and hasattr(v, '__get__'): >> ... return v.__get__(self, self.__class__) >> ... return v > > I may be missing the subtlety of what you're up to, but why is overriding __getattribute__ more desirable than simply defining the descriptor in a subclass? i.e., class MyClass3(MyClass1): def __init__(self, bar=None): if bar is not None: self.bar = bar baaz = DummyDescriptor() Michael From steve at REMOVETHIScyber.com.au Mon Mar 27 11:31:04 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 28 Mar 2006 02:31:04 +1000 Subject: object references References: <1143351204.139672.36490@i39g2000cwa.googlegroups.com> Message-ID: On Sat, 25 Mar 2006 21:33:24 -0800, DrConti wrote: > Dear Python developer community, > I'm quite new to Python, so perhaps my question is well known and the > answer too. > > I need a variable alias ( what in other languages you would call "a > pointer" (c) or "a reference" (perl)) Others have given you reasons why you can't do this, or shouldn't do this. In general, I agree with them -- change your algorithm so you don't need indirect references. But if you can't get away from it, here is another work-around that might help: > class ObjectClass: > """ Test primary Key assignment """ > > if __name__ == "__main__": > > ObjectClassInstantiated=ObjectClass() > ObjectClassInstantiated.AnAttribute='First PK Elem' > ObjectClassInstantiated.AnotherOne='Second PK Elem' > ObjectClassInstantiated.Identifier=[] > ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnAttribute) > ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnotherOne) > print ObjectClassInstantiated.Identifier > ObjectClassInstantiated.AnAttribute='First PK Elem Changed' > print ObjectClassInstantiated.Identifier # helper class class Indirect: def __init__(self, value): self.value = value def mutate(self, newvalue): self.value = newvalue def __eq__(self, other): return self.value == other def __repr__(self): return "-> %r" % self.value instance = ObjectClass() instance.attribute = Indirect('First PK Elem') instance.another_attribute = Indirect('Second PK Elem') instance.identifier = [instance.attribute, instance.another_attribute] print instance.identifier instance.attribute.mutate('First PK Elem Changed') print instance.identifier which prints [-> 'First PK Elem', -> 'Second PK Elem'] [-> 'First PK Elem Changed', -> 'Second PK Elem'] as requested. -- Steven. From mforbes at lnsDOTmit.edu Fri Mar 3 01:49:11 2006 From: mforbes at lnsDOTmit.edu (Michael McNeil Forbes) Date: Thu, 2 Mar 2006 22:49:11 -0800 Subject: how to overload sqrt in a module? In-Reply-To: References: Message-ID: > On Thu, 2 Mar 2006 16:12:53 -0800, Michael McNeil Forbes wrote: > >> I would like to write a module that provides some mathematical functions >> on top of those defined in math, cmath etc. but I would like to make it >> work with "any" type that overloads the math functions. >> On Fri, 3 Mar 2006, Dennis Lee Bieber wrote: > Since Python doesn't dispatch based on parameter types, there are > only two choices that I can see... > > Either the CALLER already knows what the arguments are, and has > coded an explicit call to the version of the function desired... The caller does know in my case, but wants to reuse old code that performs a complicated computation using the standard math functions. I was thinking that maybe there was some way for the caller to pass the appropriate functions to the module on import, but could not find a way of doing this. > OR, the caller imports and calls your special module, and your > special module has to import ALL possible override modules and supply a > function that determines which of the modules is to be used... This is essentially what numpy.sqrt() etc. does as pointed out by Robert Kern. The numpy.sqrt() seems to check if the argument is real, complex, or some other type and calls either math.sqrt, cmath.sqrt or x.sqrt() appropriately. This works for my problem: I just wondered if there was a more generic solution without having to do this work. Thanks, Michael. From dag at viz.no Sun Mar 19 16:06:13 2006 From: dag at viz.no (Dag Sunde) Date: 19 Mar 2006 22:06:13 +0100 Subject: Xah's Edu Corner: What is Expressiveness in a Computer Language References: <1142490052.127055.50130@v46g2000cwv.googlegroups.com> <1142802198.068034.157610@g10g2000cwb.googlegroups.com> Message-ID: <441dc7c5@news.wineasy.se> "Xah Lee" wrote in message news:1142802198.068034.157610 at g10g2000cwb.googlegroups.com... > What is Expressiveness in a Computer Language PLONK. -- Dag. From bencvt at gmail.com Sun Mar 5 15:11:43 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 5 Mar 2006 12:11:43 -0800 Subject: Separating elements from a list according to preceding element In-Reply-To: <1141587629.918414.245530@t39g2000cwt.googlegroups.com> References: <1141587629.918414.245530@t39g2000cwt.googlegroups.com> Message-ID: <1141589503.057501.288950@p10g2000cwp.googlegroups.com> Rob Cowie wrote: > I wish to derive two lists - each containing either tags to be > included, or tags to be excluded. My idea was to take an element, > examine what element precedes it and accordingly, insert it into the > relevant list. However, I have not been successful. > > Is there a better way that I have not considered? Maybe. You could write a couple regexes, one to find the included tags, and one for the excluded, then run re.findall on them both. But there's nothing fundamentally wrong with your method. > If this method is > suitable, how might I implement it? tags = ['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4'] include, exclude = [], [] op = '+' for cur in tags: if cur in '+-': op = cur else: if op == '+': include.append(cur) else: exclude.append(cur) --Ben From jstroud at ucla.edu Wed Mar 8 17:40:27 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 08 Mar 2006 14:40:27 -0800 Subject: Checking function calls In-Reply-To: References: Message-ID: Fredrik Tolf wrote: > On Mon, 2006-03-06 at 20:25 -0800, James Stroud wrote: > >>Fredrik Tolf wrote: >> >>>If I have a variable which points to a function, can I check if certain >>>argument list matches what the function wants before or when calling it? >>> >>>Currently, I'm trying to catch a TypeError when calling the function >>>(since that is what is raised when trying to call it with an illegal >>>list), but that has the rather undesirable side effect of also catching >>>any TypeErrors raised inside the function. Is there a way to avoid that? >>> >>>Fredrik Tolf >>> >>> >> >>Since python is "weakly typed", you will not be able to check what >>"type" of arguments a function expects. [...] > > > Sorry, it seems I made myself misunderstood. I don't intend to check the > type of the values that I pass to a function (I'm well aware that Python > is dynamically typed). The reason I refer to TypeError is because that > seems to be the exception raised by Python when I attempt to call a > function with an argument list that wouldn't be valid for it (for > example due to the number of parameters being wrong). I just want to > check in advance whether a certain arglist would be valid to call a > certain function. > > >>So, if you want to know the number of >>arguments expected, I've found this works: >> >>py> def func(a,b,c): >>... print a,b,c >>... >>py> func.func_code.co_argcount >>3 > > > Not very well, though: > >>>>def a(b, c, *d): pass > > ... > >>>>print a.func_code.co_argcount > > 2 > > Here, that would indicate that I could only call `a' with two arguments, > while in fact I could call it with two or more arguments. > > More exactly, what I'm trying to do is this; I writing a small protocol > server class as part of a program, and I thought it would be convenient > to be able to define new commands in the protocol by just adding a > function for them, like this: > > class client: > # ... > # Read is called from the event driver when data is available on the > # socket. > def read(self): > self.buf += self.sk.recv(65536) > for c in self.buf.split("\n")[:-1]: > cv = tokenize(c) > if len(cv) > 0: > f = getattr(self, "cmd_" + cv[0], None) > if callable(f): > f(*cv[1:]) > else: > self.reply("err", "unk") > # Example: > def cmd_echo(self, arg1): > self.reply("ok", arg1) > > So basically, I want to be able to handle to client giving the wrong > number of arguments and reply with an error rather than the server > process crashing and dying. Therefore, I'm currently catching TypeErrors > when calling the function: > > # ... > if callable(f): > try: > f(*cv[1:]) > except TypeError: > self.reply("err", "argno") > # ... It might be more reasonable to program your cmd_* functions to be more flexible themselves. This would be more pythonic. E.g. def cmd_echo(self, *args): if not len(args): answer = 'OMITTED' # or raise your own exception else: answer = args[0] self.reply("ok", answer) Now, you never have to worry about length of the argument list. You could, of course factor this behavior. Here's how I might do it: # first make a custom exception class, called whatever you want class ServerError(exception): pass #... somewhere in your client class def preprocess_args(self, args, numexpected): """ This is the more flexible way. A less flexible way would to check for the exact number of arguments. But that goes against the "lenient in what you accept" maxim. """ if len(args) < numexpected: raise ServerError, 'Too few args!' else: return args[:numexpected] def cmd_echo(self, *args): (answer,) = preprocess_args(args, 1) # preprocess returns tuple self.reply("ok", answer) #... elsewhere in your client class if callable(f): try: f(*cv[1:]) except ServerError, e: self.reply("err", "argno") # can also make use of exception e You could factor even further with a dictionary: minargs = {'echo' : 1, 'etc' : 5000} #... somewhere in your client class def preprocess_args(self, cv): """ This is the more flexible way. A less flexible way would to check for the exact number of arguments. But that goes against the "lenient in what you accept" maxim. """ args = cv[1:] expected = minargs[cv[0]] if len(args) < expected: raise ServerError, 'Too few args!' else: return args[:expected] # ... def cmd_echo(self, answer): self.reply("ok", answer) # ... elsewhere if callable(f): try: args = preprocess_args(cv) except ServerError, e: self.reply("err", "argno") # can also make use of exception e f(*args) Now you shouldn't have to rewrite any cmd_* functions. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From johnjsal at NOSPAMgmail.com Mon Mar 6 16:12:53 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 06 Mar 2006 21:12:53 GMT Subject: Need help initializing a list or tuple. In-Reply-To: <1141675010.414126.321400@j33g2000cwa.googlegroups.com> References: <1141664498.539402.43160@e56g2000cwe.googlegroups.com> <1141675010.414126.321400@j33g2000cwa.googlegroups.com> Message-ID: KraftDiner wrote: > nope.. sorry its not... > I meant x = [[1,2,3],[3,4,5],[5,6,7]] > Whew, you were about to really throw me for a loop otherwise! :) From kent at kentsjohnson.com Fri Mar 3 09:26:06 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 03 Mar 2006 09:26:06 -0500 Subject: Convert dictionary to HTTP POST In-Reply-To: References: <4408084D.4060708@designaproduct.biz> Message-ID: <44084d4e$1_1@newspeer2.tds.net> Laszlo Zsolt Nagy wrote: > The values of some inputs are encoded using html entities. > How can I decode a string like "Bessy's cat" in "Bessy's cat"? http://groups.google.com/group/comp.lang.python/browse_frm/thread/819731a536a4c1a2/fce6c2f6c3d46e9c?q=htmlentitydefs&rnum=2#fce6c2f6c3d46e9c Kent From cyborg4 at walla.co.il Thu Mar 2 09:45:25 2006 From: cyborg4 at walla.co.il (cyborg4 at walla.co.il) Date: 2 Mar 2006 06:45:25 -0800 Subject: filename variables Message-ID: <1141310725.841335.173340@i40g2000cwc.googlegroups.com> If in Windows XP I use: openstring= "test.py >foo.txt" os.system(openstring) it works. But if I use: file1='foo.txt' openstring= "test.py >"+file1 It gives an IOError about no such file or directory as \\mydidr\\foo.txt What does it mean ? From No.Spam at Spam.none Tue Mar 21 14:16:36 2006 From: No.Spam at Spam.none (I. Myself) Date: Tue, 21 Mar 2006 19:16:36 GMT Subject: Release: vizann-2.0 Tkinter Neural Net Demo Program Message-ID: Release Name: vizann-2.0 This freeware program may be downloaded from http://sourceforge.net/projects/annevolve. *Notes:* This is a program to graphically demonstrate the operational details of two types of ANN (Artificial Neural Network) when used to implement the XOR function. The program is 100% GUI, meaning that there is no line-by-line input nor output. The program is written in Python. (a free download from http://www.python.org) The .zip file contains only these five files: VizANN.py - The program source code VizANN.txt - documentation xormlp.gif - an image file which VizANN.py will display xorfcba.gif - an image file which VizANN.py will display VizANNnotes.txt - this file Mitchell Timin -- I'm proud of http://ANNEvolve.sourceforge.net. I'm currently working on a major update of the SailChallenge package. If you want to write software, or articles, or do testing for ANNEvolve, let me know. Humans may know that my email address is zenguy at shaw dot ca. From jstroud at ucla.edu Mon Mar 6 15:53:25 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 06 Mar 2006 12:53:25 -0800 Subject: processing the genetic code with python? In-Reply-To: <1141657404.593850.151930@e56g2000cwe.googlegroups.com> References: <1141657404.593850.151930@e56g2000cwe.googlegroups.com> Message-ID: nuttydevil wrote: > I have many notepad documents that all contain long chunks of genetic > code. They look something like this: > > atggctaaactgaccaagcgcatgcgtgttatccgcgagaaagttgatgcaaccaaacag > tacgacatcaacgaagctatcgcactgctgaaagagctggcgactgctaaattcgtagaa > agcgtggacgtagctgttaacctcggcatcgacgctcgtaaatctgaccagaacgtacgt > ggtgcaactgtactgccgcacggtactggccgttccgttcgcgtagccgtatttacccaa > > Basically, I want to design a program using python that can open and > read these documents. However, I want them to be read 3 base pairs at a > time (to analyse them codon by codon) and find the value that each > codon has a value assigned to it. An example of this is below: > > ** If the three base pairs were UUU the value assigned to it (from the > codon value table) would be 0.296 > > The program has to read all the sequence three pairs at a time, then I > want to get all the values for each codon, multiply them together and > put them to the power of 1 / the length of the sequence in codons > (which is the length of the whole sequence divided by three). > > However, to make things even more complicated, the notebook sequences > are in lowercase and the codon value table is in uppercase, so the > sequences need to be converted into uppercase. Also, the Ts in the DNA > sequences need to be changed to Us (again to match the codon value > table). And finally, before the DNA sequences are read and analysed I > need to remove the first 50 codons (i.e. the first 150 letters) and the > last 20 codons (the last 60 letters) from the DNA sequence. I've also > been having problems ensuring the program reads ALL the sequence 3 > letters at a time. > > I've tried various ways of doing this but keep coming unstuck along the > way. Has anyone got any suggestions for how they would tackle this > problem? Yes: use python. > Thanks for any help recieved! > I couldn't help myself. I strongly suggest you study this example. It will cut your coding time way down in the future. I'm writing your name down and this is the last time I'm doing homework for you. James from operator import mul table = { 'AUG' : 0.98999, 'CCC' : 0.9755 } # <== you fill this in trim_front = 50 trim_back = 20 # Why I did this: # Python >=1 line per thought; you have to love it data = "".join([s.strip() for s in open(filename)]) data = data.upper().replace('T', 'U') codons = [data[i:i+3] for i in xrange(0, len(data), 3)] # Alex Martelli trimmed = codons[trim_front:-trim_back] product = reduce(mul, [table[codon] for codon in codons]) value = product**(1.0/len(trimmed)) # <== is this really ALL codons? print value # useless print statement -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From abbi_0382 at yahoo.com Mon Mar 6 02:05:31 2006 From: abbi_0382 at yahoo.com (anushya beauty) Date: Sun, 5 Mar 2006 23:05:31 -0800 (PST) Subject: setting PYTHONPATH Message-ID: <20060306070531.50187.qmail@web50110.mail.yahoo.com> Hi, Anybody, please help me to set PYTHONPATH to import my modules?. Where is sy.path set? In some python groups site, to import the user modules, they explained to create one __init__.py file in my module directory (this file should include __all__ variable, which refer to the modules that the user wants to import). How to set the __all__ var? Thanks and Regards, abbi --------------------------------- Yahoo! Mail Bring photos to life! New PhotoMail makes sharing a breeze. -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Sun Mar 26 10:29:50 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 26 Mar 2006 07:29:50 -0800 Subject: Module documentation References: Message-ID: <1143386990.474412.13320@g10g2000cwb.googlegroups.com> Tony Burrows wrote: > Just getting to grips with Python, a great language BUT > With something like Java I can find the syntax of a method call with no > problems, how do I do the same with Python? > > For example, using MySQLdb or SGMLParser I can see what the available > methods are with dir, but how do I find out what parameters are needed and > what they represent? You can use the help function to get documentation on modules, functions, classes and objects. For example: import sgmllib help(sgmllib) # gives lots of information on the entire module help(sgmllib.SGMLParser) # gives information on the class help(sgmllib.SGMLParser.__init__) # gives initialisation information Unfortunately, because of the discrepancies between "old-style" and "new-style" classes, you can't always get decent help on objects. Consider this contrived example: parser = sgmllib.SGMLParser() # you'd usually be using a subclass help(parser) # gives information about "class instance(object)" Compare this to what happens when you get help on a file object: f = open("/etc/hosts") help(f) # gives information about "class file(object)" Personally, I feel that the whole "new-style" thing - making a class which inherits from something called "object" (of all the names that could have been chosen) - introduces a fair number of implementation-level issues that should have been hidden at the level of the language. I know that various other object-oriented languages have "object" or "Object" as a root class, but it's a dubious convention, unnecessary for the first seven or more years of Python's public life, and perhaps a prime candidate for elimination in the much-discussed-of-late Python 3000. Paul From mneagul at gmail.com Wed Mar 29 05:21:22 2006 From: mneagul at gmail.com (mneagul) Date: 29 Mar 2006 02:21:22 -0800 Subject: mod_python bytecompiling In-Reply-To: <1143627070.805953.47730@u72g2000cwu.googlegroups.com> References: <1143625503.312591.31000@i40g2000cwc.googlegroups.com> <1143627070.805953.47730@u72g2000cwu.googlegroups.com> Message-ID: <1143627682.527563.172010@i40g2000cwc.googlegroups.com> Problem solved!!! Thank You! From timr at probo.com Fri Mar 17 02:52:04 2006 From: timr at probo.com (Tim Roberts) Date: Fri, 17 Mar 2006 07:52:04 GMT Subject: Large algorithm issue -- 5x5 grid, need to fit 5 queens plus some squares References: <1142484909.490742.152390@j33g2000cwa.googlegroups.com> Message-ID: <4ppk12dc7lf6mrjpqta0q4tlln7tcokg05@4ax.com> "Fredrik Lundh" wrote: >totalgeekdom at gmail.com wrote: > >> The problem I'm trying to solve is. >> There is a 5x5 grid. >> You need to fit 5 queens on the board such that when placed there are >> three spots left that are not threatened by the queen. > >when you're done with your homework (?), you can compare it with >Guido's solution: > > http://svn.python.org/view/python/trunk/Demo/scripts/queens.py That solves a different problem. The traditional N queens problem would be "place 5 queens so that none of them threatens another". That's very different from his problem specification. It turns out there is only 1 unique (non-rotated, non-reflected) solution to the problem as he posted it. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From alexandre.guimond at gmail.com Thu Mar 2 06:53:20 2006 From: alexandre.guimond at gmail.com (Alexandre Guimond) Date: 2 Mar 2006 03:53:20 -0800 Subject: logging to a text widget Message-ID: <1141300400.454119.57290@t39g2000cwt.googlegroups.com> Hi. I'm using the logging package. I would like to send my log messages to a Text widget creating using Tkinter. I was wondering if there was a logging handler class that would do this. It seems that the standard handlers do not support this. Has anyone tried to do this? Thx for any help, alex From steven.bethard at gmail.com Thu Mar 23 11:16:57 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 23 Mar 2006 09:16:57 -0700 Subject: multiple assignment In-Reply-To: <1143090786.649093.114960@g10g2000cwb.googlegroups.com> References: <1143018514.721434.246450@i39g2000cwa.googlegroups.com> <1143039628.881127.25010@u72g2000cwu.googlegroups.com> <1143090786.649093.114960@g10g2000cwb.googlegroups.com> Message-ID: Anand wrote: >>> Wouldn't it be nice to say >>> id, *tokens = line.split(',') >> >> id, tokens_str = line.split(',', 1) > > But then you have to split tokens_str again. > > id, tokens_str = line.split(',', 1) > tokens = tokens_str.split(',') Sorry, it wasn't clear that you needed the tokens from the original post. If you're interested in this, the best route is to write up a PEP and provide an implementation. The new AST in Python makes this kind of thing a bit easier. Steve From timr at probo.com Sat Mar 18 21:40:24 2006 From: timr at probo.com (Tim Roberts) Date: Sun, 19 Mar 2006 02:40:24 GMT Subject: Converting to ARGB and writing to a bitmap References: <1142555028.430564.4320@p10g2000cwp.googlegroups.com> Message-ID: heathimself at gmail.com wrote: > >I don't know what type of files they are, but the script allows me to >save to a bitmap just fine. But I do know they need to be in RGBA 4444 >format, so I've followed what most of the tutorials for RGBA >conversions said to do...shifting the bytes. It wasn't until I looked at your sample image that I realized you meant the INCOMING image is ARGB 4444, and you're trying to convert it to ARGB 8888. >The major problem is that everything is in green, it's shifted up by x >pixels, and it's..um..flipped from left to right. I've been working on >this for a few weeks now and any insight to the problem is greatly >appreciated. There are a couple of issues here. Depth 32 is not one of the standard formats for DIBs. 24 is (B G R B G R), but not 32. To create 32-bit DIBs, you are supposed to set biCompression to BI_BITFIELDS, and then supply bitmasks in the three dwords that follow the BITMAPINFOHEADER telling exactly where the R, G, and B values can be found. However, NT happens to handle the format as you have it, so we'll leave it alone. DIBs have no concept of an alpha channel. What are you going to use to read this? ># since bitmaps are upside down, gotta flip it over >data = f2.read() > >i = size-21 >while i >= 0: > nm = 0x100 > > f1.seek(i) > temp1 = struct.unpack('B', f1.read(1))[0] This reads one 8 bit value, and then tries to pull 32 bits of information from it. You need to read a 16-bit value and crack it 4 bits at a time, not 8 bits. > peek = temp1 > > a = nm*(peek >> 24) & 0xff > r = nm*(peek >> 16) & 0xff > g = nm*(peek >> 8 ) & 0xff > b = nm*(peek & 0xff) What is the "multiply by 0x100" supposed to be doing? As near as I can tell, since "*" binds more tightly than "&", this will result in a, r, and always being 0. > sh = (a<<24)|(r<<16)|(g<<8)|b > > f2.write(struct.pack('H', sh)) "sh" is a 32-bit value. You almost certainly want 'L' here, not 'H'. Here is one that works, although it creates the DIB upside down, as you note. I'll leave that as an exercise for the reader. import os import struct import array IN = 'testimg' OUT = 'xxx.bmp' fin = file(IN,'rb') width = 100 insize = os.stat(IN)[6] height = insize / width / 2 fout = file(OUT,'wb') # Do the BITMAPFILEHEADER. fout.write('BM') bmfh = struct.pack( 'LLL', insize*2 + 14 + 40, 0, 14+40 ) fout.write(bmfh) # Do the BITMAPINFOHEADER. bmih = struct.pack('LLLHHLLLLLL', 40, width, height, 1, 32, 0, 0, 0, 0, 0, 0 ) fout.write(bmih) # Expand the pixels, scan by scan. for i in range(height): words = array.array('H') words.fromfile( fin, width ) rgba = array.array('B') for word in words: a = ((word >> 12) & 0xf) * 0x11 r = ((word >> 8) & 0xf) * 0x11 g = ((word >> 4) & 0xf) * 0x11 b = ((word >> 0) & 0xf) * 0x11 rgba.extend( [b,g,r,a] ) rgba.tofile(fout) print '*', -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mtobis at gmail.com Fri Mar 10 20:11:54 2006 From: mtobis at gmail.com (Michael Tobis) Date: 10 Mar 2006 17:11:54 -0800 Subject: Python Evangelism In-Reply-To: References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> Message-ID: <1142039514.707128.240270@j33g2000cwa.googlegroups.com> The name isn't changing, so it's a "make lemonade" situation. What's the best use we can make of the name; how do we make it stick in people's minds positively? How do we make a positive image out of it? Shy tadpoles, by the way, ( http://python.org/images/python-logo.gif ) isn't it. mt From kent at kentsjohnson.com Sat Mar 25 07:03:19 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sat, 25 Mar 2006 07:03:19 -0500 Subject: how to format a return value by using re.sub(regx,rep1,str)? In-Reply-To: <1143276718.439741.109220@u72g2000cwu.googlegroups.com> References: <1143276718.439741.109220@u72g2000cwu.googlegroups.com> Message-ID: <44252c63$1_1@newspeer2.tds.net> dongdong wrote: > for example: > re.sub(']+)+\s?>[^<^>]*','',' asd ga href="http://www.sine.com" class="wordstyle"> asdgasdghae rha') > > I wish to get the return value "asd ga asdgasdghae rha",how do do? > I have a impression on "%" and "{number}",but forgot how to use them. > Use a group to capture the text between and : In [10]: re.sub(']+)+\s?>([^<^>]*)',r'\2',' asd ga asdgasdghae rha') Out[10]: ' asd ga asdgasdghae rha' Kent From usenetpublic-elessar.xyz at yahoo.it Sat Mar 11 15:21:44 2006 From: usenetpublic-elessar.xyz at yahoo.it (EleSSaR^) Date: Sat, 11 Mar 2006 21:21:44 +0100 Subject: "RuntimeError: dictionary changed size during iteration" ; Good atomic copy operations? References: <104lhpbuofu4l.jz32d3oa1uk7$.dlg@40tude.net> Message-ID: robert si ? profuso/a a scrivere su comp.lang.python tutte queste elucubrazioni: [cut] P.S. I'm very bad at threaded programming. Please verify any of my suggestions ^_^ -- EleSSaR^ -- Togli .xyz dalla mia email per contattarmi. From hgk at et.uni-magdeburg.de Wed Mar 15 09:21:18 2006 From: hgk at et.uni-magdeburg.de (Hans Georg Krauthaeuser) Date: Wed, 15 Mar 2006 15:21:18 +0100 Subject: FIR filtering In-Reply-To: <1142428703.224948.317700@u72g2000cwu.googlegroups.com> References: <1142428703.224948.317700@u72g2000cwu.googlegroups.com> Message-ID: LabWINC wrote: > Hi all, > i'm looking for a module to implement a digital FIR filter! > Can anyone help me? > > Thanks, > > Vincent > gnuradio? Hans Georg From mkluwe at gmail.com Thu Mar 9 11:59:05 2006 From: mkluwe at gmail.com (Matthias Kluwe) Date: 9 Mar 2006 08:59:05 -0800 Subject: StaticBoxSizer problems References: <1141848308.410869.90390@z34g2000cwc.googlegroups.com> Message-ID: <1141923545.799914.254560@v46g2000cwv.googlegroups.com> Hi! If anybody's interested, I've got an solution now. > I'd like to place several StaticBoxes in a frame, but I can't get it > right. > import wx > app = wx.PySimpleApp() > frame = wx.Frame(parent=None, title="Test") > box = wx.BoxSizer(wx.VERTICAL) > frame.SetSizer(box) > upper_box = wx.StaticBox(parent=frame, label="Upper Box") > box.Add(item=upper_box, flag=wx.GROW) > upper_sizer = wx.StaticBoxSizer(upper_box) Oops. That's a thinko. upper_box is no sizer. The right line must be box.Add(item=upper_sizer, flag=wx.GROW) > upper_sizer.Add(wx.Button(parent=frame, label="Button")) > frame.Show() > app.MainLoop() > [...] > Additionally: wx.StaticBoxSizer.__init__.__doc__ says that a > StaticBoxSizer is created by __init__(self, StaticBox box, int > orient=HORIZONTAL). But if I change the line > upper_sizer = wx.StaticBoxSizer(upper_box) > to > upper_sizer = wx.StaticBoxSizer(StaticBox=upper_box) > I get the error: TypeError: new_StaticBoxSizer() takes at least 1 > argument (0 given). This is still to be solved. Regards, Matthias From codecraig at gmail.com Thu Mar 9 15:16:47 2006 From: codecraig at gmail.com (abcd) Date: 9 Mar 2006 12:16:47 -0800 Subject: pythoncom.PumpMessages - how to quit Message-ID: <1141935407.558667.12820@j52g2000cwj.googlegroups.com> When I call: pythoncom.PumpMessages() ...it blocks at that line. According to the docs, it says it will run until it receives a WM_QUIT....so I try to create a separate thread and do import win32api win32api.PostQuitMessage() ...but the code is still blocking at PumpMessages. Any ideas? other than killing python? thanks From ethrandil at gmx.net Sun Mar 26 21:06:24 2006 From: ethrandil at gmx.net (Clemens Hepper) Date: Mon, 27 Mar 2006 04:06:24 +0200 Subject: a problem to solve In-Reply-To: <1143237220.103038.52200@t31g2000cwb.googlegroups.com> References: <5oiUf.1818$No6.41433@news.tufts.edu> <1143237220.103038.52200@t31g2000cwb.googlegroups.com> Message-ID: Hi, mensanator at aol.com wrote: > That's one way to do it. I did it that way because I have the > hex patterns memorized. You should be able to generate your numbers like this: number = int('0010010001000000100', 2) mfg - eth From steve at REMOVETHIScyber.com.au Fri Mar 10 20:59:40 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 11 Mar 2006 12:59:40 +1100 Subject: Silly import question (__file__ attribute) References: <1141941885.824586.151680@v46g2000cwv.googlegroups.com> Message-ID: On Thu, 09 Mar 2006 17:25:20 -0500, Jack Diederich wrote: > It is a built-in module so it doesn't have a .so (dll) or .py file > to mention. Wouldn't it make sense for module.__file__ to be set to None rather than completely missing in this case? -- Steven. From codecraig at gmail.com Thu Mar 9 15:16:17 2006 From: codecraig at gmail.com (abcd) Date: 9 Mar 2006 12:16:17 -0800 Subject: pythoncom.PumpMessages - how to quit Message-ID: <1141935377.438625.26390@e56g2000cwe.googlegroups.com> When I call: pythoncom.PumpMessages() ...it blocks at that line. According to the docs, it says it will run until it receives a WM_QUIT....so I try to create a separate thread and do import win32api win32api.PostQuitMessage() ...but the code is still blocking at PumpMessages. Any ideas? other than killing python? thanks From sathyaish at gmail.com Tue Mar 28 09:15:08 2006 From: sathyaish at gmail.com (Sathyaish) Date: 28 Mar 2006 06:15:08 -0800 Subject: in-place string reversal In-Reply-To: <1143554931.104392.187480@i39g2000cwa.googlegroups.com> References: <1143554931.104392.187480@i39g2000cwa.googlegroups.com> Message-ID: <1143555308.009412.295250@z34g2000cwc.googlegroups.com> And that the "extra-memory" operation I've given above is expensive, I believe. Is there an efficient way to do it? From zxo102 at gmail.com Thu Mar 23 09:35:15 2006 From: zxo102 at gmail.com (zxo102) Date: 23 Mar 2006 06:35:15 -0800 Subject: Help: why python odbc module can not fetch all over? In-Reply-To: References: <1143093403.583771.152450@i39g2000cwa.googlegroups.com> Message-ID: <1143124515.569270.321370@u72g2000cwu.googlegroups.com> Hi Dennis, Thanks for your effort. I really appreciate it. It works for me now. Ouyang From http Wed Mar 29 06:35:19 2006 From: http (Paul Rubin) Date: 29 Mar 2006 03:35:19 -0800 Subject: any() and all() on empty list? References: <1143622860.716668.231370@v46g2000cwv.googlegroups.com> Message-ID: <7xhd5h1o20.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > While the implemented behaviour might be more practical than the > alternatives, it is still worrying paradoxical. If "All sheep are woolly", > then obviously it must also be true that "Any sheep is woolly". More > formally, if all(X), then any(X) -- except for the case of empty X. Hmmm. Maybe "any" should be renamed to "some". From paddy3118 at netscape.net Mon Mar 13 14:41:20 2006 From: paddy3118 at netscape.net (Paddy) Date: 13 Mar 2006 11:41:20 -0800 Subject: Python Love :) In-Reply-To: References: <1142099350.122968.35220@i39g2000cwa.googlegroups.com> <1142152271.545155.268170@i40g2000cwc.googlegroups.com> <1142186313.502716.126710@z34g2000cwc.googlegroups.com> Message-ID: <1142278880.811619.182560@u72g2000cwu.googlegroups.com> BWill wrote: > and ixnay on the ubyray or else I'll tell you where to stick your > endblock delimiter :P Umm, Did you mean to write the above? What has it to do with Ruby? From caleb.hattingh at gmail.com Tue Mar 28 16:20:02 2006 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 28 Mar 2006 13:20:02 -0800 Subject: Multiplying sequences with floats In-Reply-To: References: <1143239583.002604.44010@v46g2000cwv.googlegroups.com> Message-ID: <1143580802.212165.142880@t31g2000cwb.googlegroups.com> Hi Fredrik Fair enough; I wasn't precise. Upon further reflection, I actually meant floor division, via the // operator. In the following snippet: >>> 4/2 2 >>> 4//2 2 >>> 4.0/2.0 2.0 >>> 4.0//2 2.0 >>> 4.0//2.0 2.0 We know the last two operations can only return what are effectively integer numbers (or raise an error), but the type that gets returned for a valid operation is a float. Now, I'm not pretending to know much about this stuff, just pointing out that that behaviour is interesting. Just like how MvL pointed out to me in a recent thread that in certain cases .read().splitlines(True) is significantly faster than .readlines() on some file objects: that's interesting. I am sure there are good reasons for this, and I can't imagine that the issue of return type didn't come up when discussions about the floor division operator was discussed; in fact, thinking about it a little more, I suspect this operator is probably more likely to be used in a sequence of floating-point operations anyway, for which the current implementation saves a type conversion that might have been necessary had it been made to return int to start with. So regarding my previous statement: >> I agree that integer division should return an integer, >> because using the operator at all means you expect one. I am not so sure now :) By the way (regarding PIL), have you seen this site: http://www.greyc.unicaen.fr/~dtschump/greycstoration/index.html It is an open-source project implementing fancy methods for cleaning up images and (my interest) resizing images with better clarity on enlargements. I had been working on a python implementation for this kind of thing with heavy leaning on the PIL, but I saw this project on the daily freshmeat newsletter, and so will probably use that code instead. regards Caleb From wildemar at freakmail.de Fri Mar 3 05:15:22 2006 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 03 Mar 2006 11:15:22 +0100 Subject: getting the reference count of an object ... Message-ID: <4408173A.2030708@freakmail.de> ... how? I'm writing an app that holds a public data dictionary from which other objects obtain part of their __dict__ values so they all work on the same dataset (yes I'm fiendishly clever and a constructor of unreadable sentences (and code) ;)). My problem is that I haven't found an easy way to determine if said dictionary contents are still in use (so it is ok to delete them from the dictionary). I've thought about creating a dict subclass that counts the number of assignments and deletions but that seems cumbersome (an bug-prone). Is there a way to get the reference count of these datadict items? I imagine that this would be a more stable implementation of such a feature. Hope this gets my problem accross; if not just bash me and I'll reformulate. I'm not the best of explainers. Oh, and sorry if the solution to my problem is obvious (such as an __refcount__ attribute or some stupid oversight like that). c.u. wildemar From gshepherd281281 at yahoo.com Sat Mar 25 16:41:44 2006 From: gshepherd281281 at yahoo.com (ProvoWallis) Date: 25 Mar 2006 13:41:44 -0800 Subject: noobie mkdir problem/question Message-ID: <1143322904.618585.188740@t31g2000cwb.googlegroups.com> Hi, I'm trying to write a script that will create a new directory and then write the results to this newly created directory but it doesn't seem to work for me and I don't know why. I'm hoping someone can see my mistake or at least point me in the right direction. I start like this capturing the root directory and making my new "xrefs" directory (I can see the new folder in windows explorer): root = raw_input("Enter the path where the program should run: ") xrefs = os.path.join(root,'xrefs') if (os.path.isdir(xrefs) == 0): os.mkdir(xrefs) else: sys.exit('LOG folder already exists. Exiting program.') ...I do everything else... And then I'm trying to write the results out to xrefs. But instead of writing to xrefs they're written to the original directory, i.e., root. and I'm not sure why. outputFname = given + '.log' outputFile = open(os.path.join(xrefs,outputFname), 'w') outputFile.write(data) outputFile.close() Anyone? Thanks, Greg From p.r.hariram at gmail.com Tue Mar 7 08:30:07 2006 From: p.r.hariram at gmail.com (Hari) Date: 7 Mar 2006 05:30:07 -0800 Subject: Getting File Permissions Message-ID: <1141738207.892095.56780@p10g2000cwp.googlegroups.com> Hi, For getting permissions of a file, the following script has been suggested in the same group import os, stat st = os.stat(myfile) mode = st[stat.ST_MODE] print "mode is", octal(mode & 0777) But while executing I am getting error message as follows Traceback (most recent call last): File "", line 1, in ? NameError: name 'octal' is not defined Since I am new to python, can any one help me to solve this error? A bunch of thanks in advance. Hari From cfajohnson at gmail.com Wed Mar 29 18:04:30 2006 From: cfajohnson at gmail.com (Chris F.A. Johnson) Date: Wed, 29 Mar 2006 18:04:30 -0500 Subject: symbolic links, aliases, cls clear References: <1143672131.167324.36920@i39g2000cwa.googlegroups.com> Message-ID: On 2006-03-29, mp wrote: > i have a python program which attempts to call 'cls' but fails: > > sh: line 1: cls: command not found > > i tried creating an alias from cls to clear in .profile, .cshrc, and > /etc/profile, but none of these options seem to work. Why not call 'clear', since 'cls' does not exist? > my conclusion is that a python program that is executing does not use > the shell (because it does not recognize shell aliases). is this > correct? Even shell scripts do not normally expand aliases. > should i use a symbolic link? if so, where should i place it? > > what is the difference between aliases and symbolic links? What's the difference between a raven and a writing desk? > if i execute a command like 'clear' to clear the screen, where does the > shell look to find the command 'clear'? In a directory listed in the PATH variable. -- Chris F.A. Johnson, author | Shell Scripting Recipes: | My code in this post, if any, A Problem-Solution Approach | is released under the 2005, Apress | GNU General Public Licence From tuvas21 at gmail.com Sat Mar 4 23:01:34 2006 From: tuvas21 at gmail.com (Tuvas) Date: 4 Mar 2006 20:01:34 -0800 Subject: A simple question Message-ID: <1141531294.575847.273330@j33g2000cwa.googlegroups.com> I know the answer is probably really simple to this, and I feel bad to even ask, but I can't find the answer anywhere... Let me show what happened, then ask the question. >>> x=[[0]*2]*2 >>> x [[0, 0], [0, 0]] >>> x[0][1]=1 >>> x [[0, 1], [0, 1]] >>> The question now. Why is the output list [[0, 1], [0, 1]] and not [[0, 1], [0, 0]]? And how can I make it work right? I do know that x[0][1] will always give the value of that specific coordinate, but never before have I tried to manipulate rows like this, and I'm finding I need to. Thanks! From steve at holdenweb.com Fri Mar 10 06:53:08 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 10 Mar 2006 11:53:08 +0000 Subject: Python Evangelism In-Reply-To: <20060310053117.06d505a4@samwise.anansi> References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> <1141980825.306512.59850@j33g2000cwa.googlegroups.com> <44114A97.3060200@optushome.com.au> <20060310053117.06d505a4@samwise.anansi> Message-ID: Terry Hancock wrote: > On Fri, 10 Mar 2006 20:44:55 +1100 > Tim Churches wrote: > >>I think that Glykon should be invited to be the sponsoring >>divinity for PyCon next year. I hear that worship of pagan >>gods is, like everything else, bigger in Texas. > > > Ignoring the silly Python jokes, *is* PyCON going to be in > Texas next year? I wasn't sure what would happen, since it > was in Washington DC the last (first?) 3 years, according to > the website. Would be great for me if true, since I live > there. > Yes, 2007 will be at the same place as 2006. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From http Wed Mar 8 19:48:05 2006 From: http (Paul Rubin) Date: 08 Mar 2006 16:48:05 -0800 Subject: Problem Solving Skills for Engineers References: <1141865179.442845.89120@j33g2000cwa.googlegroups.com> Message-ID: <7x8xrksat6.fsf@ruckus.brouhaha.com> bparanj at gmail.com writes: > I have been a software developer for the past 10 years now. I get job > descriptions that requires problem-solving skills as one of the most > desirable skills in a candidate. But there are not many resources that > is devoted to this topic. > > So, I have created a website for problem solving skills, please check > it out at [url]. That site is too spamlike for my tastes. George Polya's classic book "How to Solve It" is still very good. From deets at nospam.web.de Tue Mar 14 16:57:45 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 14 Mar 2006 22:57:45 +0100 Subject: elementtree and gbk encoding In-Reply-To: References: Message-ID: <47osiqFgp2hlU1@uni-berlin.de> Steven Bethard schrieb: > I'm having trouble using elementtree with an XML file that has some > gbk-encoded text. (I can't read Chinese, so I'm taking their word for > it that it's gbk-encoded.) I always have trouble with encodings, so I'm > sure I'm just screwing something simple up. Can anyone help me? > > Here's the interactive session. Sorry it's a little verbose, but I > figured it would be better to include too much than not enough. I > basically expected et.ElementTree(file=...) to fail since no encoding > was specified, but I don't know what I'm doing wrong when I use > codecs.open(...) The first and most important lesson to learn here is that well-formed XML must contain a xml-header that specifies the used encoding. This has two consequences for you: 1) all xml-parsers expect byte-strings, as they have to first read the header to know what encoding awaits them. So no use reading the xml-file with a codec - even if it is the right one. It will get converted back to a string when fed to the parser, with the default codec being used - resulting in the well-known unicode error. 2) your xml is _not_ well-formed, as it doesn't contain a xml-header! You need ask these guys to deliver the xml with header. Of course for now it is ok to just prepend the text with something like . But I'd still request them to deliver it with that header - otherwise it is _not_ XML, but just something that happens to look similar and doesn't guarantee to be well-formed and thus can be safely fed to a parser. HTH Diez From eoinrogers at gmail.com Fri Mar 17 15:41:16 2006 From: eoinrogers at gmail.com (Byte) Date: 17 Mar 2006 12:41:16 -0800 Subject: Importing an output from another function In-Reply-To: <1142627019.614450.250540@i40g2000cwc.googlegroups.com> References: <1142626528.204581.179350@v46g2000cwv.googlegroups.com> <1142627019.614450.250540@i40g2000cwc.googlegroups.com> Message-ID: <1142628076.041352.320560@i40g2000cwc.googlegroups.com> Great, thanks -- /usr/bin/byte From greg.kujawa at gmail.com Thu Mar 9 12:03:00 2006 From: greg.kujawa at gmail.com (gregarican) Date: 9 Mar 2006 09:03:00 -0800 Subject: Python Evangelism In-Reply-To: References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> Message-ID: <1141923780.377429.177460@u72g2000cwu.googlegroups.com> rtilley wrote: > It would be a smashing success. And I have an idea for a party game. It's called "Jump to Conclusions." There would be a mat with all of these conclusions written down and... From duncan.booth at invalid.invalid Sun Mar 5 15:44:33 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Mar 2006 20:44:33 GMT Subject: Python advocacy in scientific computation References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> <1141583453.403143.189400@i40g2000cwc.googlegroups.com> <1141589892.094037.18410@i40g2000cwc.googlegroups.com> Message-ID: sturlamolden wrote: > First there are a few things I don't like: > > 1. Intendation as a part of the syntax, really annoying. Each to his own. I find having the compiler enforce indentation rules is a real benefit. There's nothing quite so annoying as having 'coding standards' you are supposed to be following which aren't enforced (so nobody else working on the code followed them either). C code which never executes a for loop because of a spurious ';' can be pretty annoying too. > > 2. The "self.something" syntax is really tedious (look to ruby)! I find it really useful to use a similar style when programming in other languages such as Java or C#. In particular it means that you can instantly see when you are referring to a member variable (without having to prefix them all with m_ or some other abomination) and when you have method arguments which get assigned to member variables you don't have to think of different names for each. > > 4. Multithreading and parallel execution is impossible AFAIK because of > the so-called GIL (global interpreter lock). Matlab is perhaps even > worse in this respect. Multithreading and parallel execution work fine. The only problem is that you don't get the full benefit when you have multiple processors. This one will become more of an annoyance in the future though as more systems have hyperthreading and multi-core processors. > > And there is a couple of questions I need answered: > > 1. Can python do "pass by reference"? Are datastructures represented by > references as in Java (I don't know yet). > Python only does "pass by reference", although it is more normally referred to as "pass by object reference" to distinguish it from language where the references refer to variables rather than objects. What it doesn't do is let you rebind a variable in the caller's scope which is what many people expect as a consequence of pass by reference. If you pass an object to a function (and in Python *every* value is an object) then when you mutate the object the changes are visible to everything else using the same object. Of course, some objects aren't mutable so it isn't that easy to tell that they are always passed by reference. From john_sips_tea at yahoo.com Wed Mar 15 15:39:30 2006 From: john_sips_tea at yahoo.com (john_sips_tea at yahoo.com) Date: 15 Mar 2006 12:39:30 -0800 Subject: Tried Ruby (or, "what Python *really* needs" or "perldoc!") In-Reply-To: <1142434139.499666.281590@v46g2000cwv.googlegroups.com> References: <1142355126.757569.42160@i40g2000cwc.googlegroups.com> <1142397587.151040.35450@j33g2000cwa.googlegroups.com> <1142434139.499666.281590@v46g2000cwv.googlegroups.com> Message-ID: <1142455170.389577.320760@j52g2000cwj.googlegroups.com> msoulier wrote: > > [snip] > But, if Python would match Perl for docs available on the command-line, > then I'd have it all at my fingertips. I simply don't understand why > this is not being done. [snip] > > Mike Ok, well, here's my attempt to begin to make that happen: http://www.simisen.com/jmg/cpd/ This "release" is as alpha as alpha gets. It's so alpha it actually loops back around to zeta -- but it's a start, and I think it's exactly what the Python community needs. The command to read the docs works like pydoc but is called dennis (extra points for getting the obscure Monty Python reference before reading the web page). :) The dennis command is only a few lines of Python held together by bailing wire, so it will need lots of work, but it lets us read the docs so it's ok for now. You're invited to fix it up and send me an improved version. :) Please have a look and let me know what you think. If people start writing modules (that is, documentation) and sending them to me, I'll probably be forced to start a mailing list and actually put this stuff in CVS/SVN/bzr. Have at it! :) ---John From rurpy at yahoo.com Mon Mar 20 09:42:36 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 20 Mar 2006 06:42:36 -0800 Subject: Python equivalent of Perl-ISAPI? In-Reply-To: <1142790625.227356.48830@i40g2000cwc.googlegroups.com> References: <1142657781.197131.222440@g10g2000cwb.googlegroups.com> <1142790625.227356.48830@i40g2000cwc.googlegroups.com> Message-ID: <1142865756.452672.57930@v46g2000cwv.googlegroups.com> Waldemar Osuch wrote: > What Roger says and also: > http://pyisapie.sourceforge.net/ Thanks for your and Roger's responses. I looked at pyisapie and there seems to be almost no dvcumentation -- no sample code and the single readme is pretty opaque. The pywin isapi has a couple of examples but its documentation too is pretty bad. But they both seem to be tissue thin wtrappers around the MS isapi api. What I was hoping for is something that would let me run existing cgi scripts efficiently with minimal changes. I think the isapi and perl-ex stuff that comes with Activestate's Perl meets this requirement but the stuff I've found for Python doesn't. So looks like it's back to Perl for this project :-(. From duncan.booth at invalid.invalid Fri Mar 10 04:51:19 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Mar 2006 09:51:19 GMT Subject: creating variable in root namespace from module References: <1141976796.594066.229210@e56g2000cwe.googlegroups.com> Message-ID: MakaMaka wrote: > I have a scope related question that I haven't been able to find an > answer to anywhere. Is there a way to have a function in an imported > module add variables to the scope of the calling script? Basically, > can I have the following: > > #root.py > import some_module.py > > some_module.afunction() # <== create a variable x1=1 and add it to the > scope of root.py > > print x1 # <== would print 1 > > I know this can be accomplished by passing the what globals() returns > into the function; however, I'm wondering if there is a way to do this > without passing anything to the function. Try: x1 = some_module.afunction() This has the advantage that in some other script you can decide to give the variable a meaningful name, and it doesn't have to be the same as the name you used in your first script. You can easily extend this technique to set several variables in the calling script: x1, y2, z3 = some_module.afunction() You don't even have to restrict yourself to global variables, this technique will even work to let the function set variables in another function's local namespace or attributes on some arbitrary object. From anil.pundoor at gmail.com Mon Mar 6 01:07:54 2006 From: anil.pundoor at gmail.com (anil.pundoor at gmail.com) Date: 5 Mar 2006 22:07:54 -0800 Subject: Tix Note Book Message-ID: <1141625274.483448.37600@v46g2000cwv.googlegroups.com> hi am using Tix notebook and i have two frames in that. am adding some widgets in to both of the frames. now i want to delete all of the widgets in one of the frame. i dont want to delete the frame, but its childres. so how can i get the sub widgets within that frame. Thanks in advance Anil From mkluwe at gmail.com Fri Mar 10 12:28:43 2006 From: mkluwe at gmail.com (Matthias Kluwe) Date: 10 Mar 2006 09:28:43 -0800 Subject: StaticBoxSizer problems References: <1141848308.410869.90390@z34g2000cwc.googlegroups.com> <1141919244.683761.21050@j33g2000cwa.googlegroups.com> Message-ID: <1142011723.313281.33760@z34g2000cwc.googlegroups.com> Hi! Steve Holden wrote: > Did you actually try removing the line and running the program? I tried, of course :-) Removing the line box.Add(item=upper_box, flag=wx.GROW) yields the remaining program import wx app = wx.PySimpleApp() frame = wx.Frame(parent=None, title="Test") box = wx.BoxSizer(wx.VERTICAL) frame.SetSizer(box) upper_box = wx.StaticBox(parent=frame, label="Upper Box") upper_sizer = wx.StaticBoxSizer(upper_box) upper_sizer.Add(wx.Button(parent=frame, label="Button")) frame.Show() app.MainLoop() >> Hmm. As I see it, this means constructing the StaticBox and not placing >> it in the frame. Obviously, this does not help. > Guess what: the button appears inside the static box sizer. And your problem > with that would be ... ? ... the StaticBox not being displayed. >> "a methodical approach to GUI construction"? Please be more specific -- >> any hints are welcome. Clearly, the above is an experiment with >> wxPython, not anything methodical. This may follow when I understand >> how StaticBoxSizer works. > Well, "methodical" would seem to include testing the suggestions of > well-meaning fellow netizens, for a start, rather than using your > psychic powers to predict results. No prediction needed :-) I can't see how I have suggested you're not well-meaning. Regards, Matthias From msuemnig at jjhill.org Wed Mar 29 18:34:34 2006 From: msuemnig at jjhill.org (msuemnig at jjhill.org) Date: 29 Mar 2006 15:34:34 -0800 Subject: Apache and Python and Ubuntu In-Reply-To: <87k6ac7tgl.fsf@ieee.org> References: <1143672083.347654.81330@v46g2000cwv.googlegroups.com> <87k6ac7tgl.fsf@ieee.org> Message-ID: <1143675274.665079.244110@i40g2000cwc.googlegroups.com> Thanx a lot for your input and advice. I went through the documentation on httpd.apache.org/docs/2.2/howto/cgi.html and added the following: AddModule cgi-script .cgi .py Options +ExecCGI It now gives me a 403 forbidden. When I check the error logs, it still says that Options ExecCGI is not turned on in /var/www/ Is there a special place inside of apache2.conf I'm supposed to have the tag? and/or AddModule line? I also double checked to make sure owner/group/other all have execute and it does. From bill.scherer at verizonwireless.com Thu Mar 2 14:15:30 2006 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Thu, 02 Mar 2006 14:15:30 -0500 Subject: how do you move to a new line in your text editor? In-Reply-To: References: <%ZGNf.1711$No6.40016@news.tufts.edu> <1141325510.264691.215260@t39g2000cwt.googlegroups.com> Message-ID: <44074452.3080502@verizonwireless.com> John Salerno wrote: >I use UltraEdit right now, and it is possible to convert spaces and tabs >back and forth, but it's just an extra step. I was thinking about trying >vim, as I've heard it's easier to learn than emacs. > > Absolutely. It's also easier to learn to ride a Huffy than a Schwinn, Hondas are easier to drive than Toyotas, and Evian is easier to drink than Poland Spring. Do yourself a favor and learn them both. Then decide which is best for you. Bill From fredrik at pythonware.com Fri Mar 10 12:04:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 10 Mar 2006 18:04:22 +0100 Subject: pyc file usage in a multi OS environment ( newbe question) References: <1142009196.036785.117190@e56g2000cwe.googlegroups.com> Message-ID: "HajoEhlers" wrote: > Since the .py file are plain python scripts i assume that these are > not causing any trouble but what about the .pyc file ? ( Which i could > not figure out what they are acutelly for - My knowledge about python > is more or less a drop of water within the python ocean ) PYC files contain cached compiled Python byte code. there's also PYO files, which are optimized PYC files (created by running Python with the -O flag). PYC and PYO files are compatible across platforms, but not across major Python releases (e.g. 2.4.X cannot use 2.3.X byte codes). note that PYC files are created automatically when PY files are imported (if there's no newer PYC file already available), and the creation process is not NFS-safe in itself, so you may end up with assorted race problems if you're not careful... From bob at passcal.nmt.edu Thu Mar 30 12:59:17 2006 From: bob at passcal.nmt.edu (Bob Greschke) Date: Thu, 30 Mar 2006 10:59:17 -0700 Subject: PIL ImageDraw line not long enough Message-ID: I've resorted to actually drawing all of the characters of the alphabet on a graph to avoid having to drag around font files. It's mostly just uppercase characters, so it's not too bad. But I noticed that some of the line segments have to be extended one pixel longer than they should be in order for the last pixel to show up. The character cells are 6 pixels wide by 8 pixels high. An "L" is drawn with Graph.line((x,y, x,y+7, x+5,y+7), Color) where the starting x and y are supplied to the function. An L works OK, but to get a "T" to look right I have to do Graph.line((x+1,y, x+5,y), Color) Graph.line((x+3,y, x+3,y+8), Color) I have to extend the vertical line to y+8, instead of y+7 to get the line segment to be drawn long enough. This is on Linux, Solaris, 2.x versions of Python, 1.1.5 version of PIL, and on Windows with the latest of everything. Am I missing a setting somewhere? Thanks! Bob From robert.kern at gmail.com Sun Mar 5 14:20:02 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 05 Mar 2006 13:20:02 -0600 Subject: Python advocacy in scientific computation In-Reply-To: <440AE82D.6040303@bryant.edu> References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> <440AE82D.6040303@bryant.edu> Message-ID: Brian Blais wrote: > Robert Kern wrote: > >>That said, we have an excellent array object far superior to Matlab's. >> >> http://numeric.scipy.org/ > > I'd like to ask, being new to python, in which ways is this array object far superior > to Matlab's? (I'm not being sarcastic, I really would like to know!) Matlab takes the view that "everything is a rank-2 matrix of floating point values." Our arrays have been N-dimensional since day one. They really are arrays, not matrices. You have complete control over the types. -- Robert Kern robert.kern at gmail.com "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 grante at visi.com Wed Mar 29 10:12:29 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 29 Mar 2006 15:12:29 -0000 Subject: sending ctrl C to a program References: <1143598503.249847.207620@j33g2000cwa.googlegroups.com> Message-ID: <122l8utdde1du1c@corp.supernews.com> On 2006-03-29, Dale Strickland-Clark wrote: >> i have a program that works very similar to tail -f in Unix It >> will need a Ctrl-C in order to break out of the program. I >> wish to run this program using python (either thru os.system() >> or some other subprocess modules) and how can i pass Ctrl-C to >> this program to terminate it in python? thanks > > Isn't SIGINT the same as ctrl-c? SIGINT is what the tty line discipline layer sends to the attached processes when it sees a receive interrupt character and canonical mode is enabled. By default the interrupt character is ctrl-C. > So something like > > import os > os.kill(1234, 2) > > would send ctrl-c to process 1234. That is, indeed, what the OP wants to do. Except there is no ctrl-C involved. That code is doing what the tty line discipline code does when _it_ see's a ctrl-C. > If you just want the process to quit, you could probably just > send it a SIGTERM, which is signal 15. -- Grant Edwards grante Yow! My uncle Murray at conquered Egypt in 53 visi.com B.C. And I can prove it too!! From exogen at gmail.com Wed Mar 22 00:23:14 2006 From: exogen at gmail.com (Brian Beck) Date: Wed, 22 Mar 2006 00:23:14 -0500 Subject: New-style Python icons References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> Message-ID: and-google at doxdesk.com wrote: > http://www.doxdesk.com/img/software/py/icons.png Great work! Add an icon for Python egg files and you've covered all the bases. -- Brian Beck Adventurer of the First Order From sukhpalsingh at hotmail.com Thu Mar 23 00:48:05 2006 From: sukhpalsingh at hotmail.com (sukhpalsingh at hotmail.com) Date: 22 Mar 2006 21:48:05 -0800 Subject: Embed Mozilla ActiveX Browser Control or MSIE the easy WAY! Message-ID: <1143092885.019631.314550@j33g2000cwa.googlegroups.com> With this little DLL you can embed either Mozilla ActiveX Browser Control or MSIE by just calling it's EmbedBrowser(HWND hwnd, int i[0,1]) function. 0 = Mozilla Activex Browser Control and 1 = MSIE. Other available methods include: >> UnEmbedBrowser() >> ResizeBrowser(HWND hwnd) Where hwnd is an handle to a control where the browser control is embedded. >> DisplayPage(STRING url) Where url is a string that contains the URL of a location to be displayed. >> DoPageActionGoBack() >> DoPageActionGoForward() >> DoPageActionRefresh() >> DoPageActionStop() You can download the DLL from: http://embedbrowser.gurugranthji.com Thanks for your attention! From neurogasm at gmail.com Sat Mar 18 16:44:44 2006 From: neurogasm at gmail.com (Kevin F) Date: Sat, 18 Mar 2006 16:44:44 -0500 Subject: POP3 Mail Download Message-ID: Having some troubles downloading messages with POP3... I can connect to the server just fine and list messages without any problem with the following code: ------------------------ from poplib import * server = POP3("mail.bluebottle.com") print server.getwelcome() print server.user("neurogasm at bluebottle.com") print server.pass_("xxxxxxxx") messagesInfo = server.list()[1] numMessages = len(messagesInfo) print numMessages ------------------------ However, if I try to actually download the messages themselves, my python editor highlights 'msgSize' and says "invalid syntax" when I run the following subsequent lines of code: ------------------------ emails = [] for msg in messagesInfo: msgNum = int(split(msg, " ")[0] msgSize = int(split(msg, " ")[1] if(msgSize < 20000): messages = server.retr(msgNum)[1] messages = join(message, "\n") emails.append(message) ------------------------ anyone know what's wrong? thanks. From arne at citde.net Thu Mar 23 16:44:54 2006 From: arne at citde.net (Arne Ludwig) Date: 23 Mar 2006 13:44:54 -0800 Subject: removing file by inode References: <1143090399.430131.224390@t31g2000cwb.googlegroups.com> <1225egub5k1kv3b@corp.supernews.com> <1143128801.255443.44910@v46g2000cwv.googlegroups.com> <1225js8nlmhbpc6@corp.supernews.com> <1143149571.388374.230420@e56g2000cwe.googlegroups.com> Message-ID: <1143150294.871222.269720@i40g2000cwc.googlegroups.com> Actually under Linux he could probably pipe "clri %d" to debugfs if that is what he wanted to do. On the other hand he said "unix environment" which could be anything really. From reply.in.the.newsgroup at my.address.is.invalid Tue Mar 14 11:39:25 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 14 Mar 2006 17:39:25 +0100 Subject: calling another python file within python References: Message-ID: Kevin: >#!/usr/bin/python > >import os >import urllib >os.system("python pyq.py ibm > text1.txt") Check the return value of os.system. >note: currently the text1.txt outputted is just blank, however if i run >the command normally as 'python pyq.py ibm' in the command line, it >works correctly and gives me the price of ibm. Same PATH, PYTHONPATH, current working directory, user,... ? -- Ren? Pijlman From gry at ll.mit.edu Wed Mar 22 21:35:14 2006 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 22 Mar 2006 18:35:14 -0800 Subject: don't understand popen2 In-Reply-To: <4421effd$0$11070$e4fe514c@news.xs4all.nl> References: <4421effd$0$11070$e4fe514c@news.xs4all.nl> Message-ID: <1143081314.235969.227640@z34g2000cwc.googlegroups.com> Martin P. Hellwig wrote: > Hi all, > > I was doing some popen2 tests so that I'm more comfortable using it. > I wrote a little python script to help me test that (testia.py): > > --------------------------------- > someline = raw_input("something:") > > if someline == 'test': > print("yup") > else: > print("nope") > --------------------------------- > > And another little thing that does it's popen2 stuff: > > --------------------------------- > import popen2 > > std_out, std_in = popen2.popen2("testia.py") > > x=std_out.readline() > print(x) > > std_in.writelines("notgood") > > x=std_out.readline() > print(x) > --------------------------------- > > Now what I expected was that I got the return one the first line: > "something:" and on the second "nope", but instead of that I got: > > >>> > something: > Traceback (most recent call last): > File "F:\coding\pwSync\popen_test\popen_test.py", line 8, in ? > std_in.writelines("notgood") > IOError: [Errno 22] Invalid argument > >>> > > I played around a bit with flush, write and the order of first writing > and then reading, the best I can get is no error but still not the > expected output. I googled a bit copied some examples that also worked > on my machine, reread the manual and the only conclusion I have is that > I don't even understand what I'm doing wrong. > > Would you please be so kind to explain my wrong doing? > (python 2.4 + win32 extensions on XPProSP2) >>> help(sys.stdin.writelines) Help on built-in function writelines: writelines(...) writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string> You gave it a single string, not a list(sequence) of strings. Try something like: std_in.writelines(["notgood"]) From grante at visi.com Thu Mar 2 18:48:28 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 02 Mar 2006 23:48:28 -0000 Subject: Write a GUI for a python script? References: <1141334921.910918.56760@i39g2000cwa.googlegroups.com> Message-ID: <120f12cbl2qdobb@corp.supernews.com> On 2006-03-02, sjdevnull at yahoo.com wrote: > Note that wxWindows wraps native widgets, Not on Linux/KDE systems. ;) -- Grant Edwards grante Yow! ANN JILLIAN'S HAIR at makes LONI ANDERSON'S visi.com HAIR look like RICARDO MONTALBAN'S HAIR! From http Sat Mar 4 16:30:41 2006 From: http (Paul Rubin) Date: 04 Mar 2006 13:30:41 -0800 Subject: add an asynchronous exception class References: <7x3bhysotm.fsf_-_@ruckus.brouhaha.com> <7xu0aemyil.fsf@ruckus.brouhaha.com> Message-ID: <7xwtf9kida.fsf@ruckus.brouhaha.com> "Christian Stapfer" writes: > I guess it means the following: > > "Terminating exceptions" are exceptions that > terminate the *thrower* of the exception. Are you sure? I didn't read it that way. I'm not aware of there ever having been a detailed proposal for resumable exceptions in Python, though the gurus would know better than I do whether there's been one. From istvan.albert at gmail.com Tue Mar 14 13:38:35 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 14 Mar 2006 10:38:35 -0800 Subject: Tree and Graph structures in Python. In-Reply-To: <1142354041.729149.26140@u72g2000cwu.googlegroups.com> References: <1142354041.729149.26140@u72g2000cwu.googlegroups.com> Message-ID: <1142361515.078137.193790@j52g2000cwj.googlegroups.com> See this: https://networkx.lanl.gov/ From mhellwig at xs4all.nl Tue Mar 14 16:39:29 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Tue, 14 Mar 2006 22:39:29 +0100 Subject: PEP 8 example of 'Function and method arguments' In-Reply-To: <44159b49$0$11065$e4fe514c@news.xs4all.nl> References: <44159b49$0$11065$e4fe514c@news.xs4all.nl> Message-ID: <44173815$0$11080$e4fe514c@news.xs4all.nl> Steven, Bruno, Terry & Duncon, thank you for your insights, it really helped me a great deal. -- mph From luca.tavoletti at gmail.com Tue Mar 14 10:29:24 2006 From: luca.tavoletti at gmail.com (lux) Date: 14 Mar 2006 07:29:24 -0800 Subject: EVT_ICONIZE lost focus Message-ID: <1142350164.357411.219510@v46g2000cwv.googlegroups.com> Hi, I have a wxFrame with some TextCtrl, if I minimize the Frame when normalize it lost the Focus and I must click to give the focus to textCtrl again How can resolve? Thank's, Luca From tjreedy at udel.edu Fri Mar 10 11:33:56 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 10 Mar 2006 11:33:56 -0500 Subject: Why python doesn't use syntax like function(, , x) for default parameters? References: <44115054$0$14937$834e42db@reader.greatnowhere.com> Message-ID: "Antoon Pardon" wrote in message news:slrne1372v.mt4.apardon at rcpc42.vub.ac.be... > but nobody seems to have > a problem with range(n) where n suddenly is the second parameter and > we use the default for the first. Actually, I consider the unique calling pattern for x/range to be something of a wart. Learning this inconsistency was at least a minor problem. It is a rather extreme example of typing laziness beats purity. Given that enumerate() eliminate many uses of range(), it might be worth considering requiring the start param. range(0,n) only takes two more keystrokes. Better maybe to shorten range to rng to get them back ;-) Terry Jan Reedy From ministeyr at free.fr Tue Mar 21 04:36:15 2006 From: ministeyr at free.fr (Ministeyr) Date: Tue, 21 Mar 2006 10:36:15 +0100 Subject: should os.walk return a list instead of a tuple? Message-ID: <441FC90F.4010108@free.fr> Hello, os.walk doc: http://www.python.org/doc/2.4/lib/os-file-dir.html#l2h-1625 When walking top to bottom, it allows you to choose the directories you want to visit dynamically by changing the second parameter of the tuple (a list of directories). However, since it is a tuple, you cannot use "filter" on it, since it would mean reassigning it: for dir_tuple in os.walk('/home'): dir_tuple[1]=filter(lambda x: not x.startswith('.'), dir_tuple[1]) #do not show hidden files print dir_tuple #just print the directory and its contents in the simplest possible way If os.walk did return a list of three items instead of a tuple, that would become possible. It would also not break old code like for dirpath, dirnames, filenames in os.walk(somedir): do something..... Since assigning a list to a tuple is valid python code. Thanks. From webraviteja at gmail.com Fri Mar 31 20:03:10 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 31 Mar 2006 17:03:10 -0800 Subject: Can I control Video Card by using Python under linux? In-Reply-To: References: <1143796342.957617.147690@i40g2000cwc.googlegroups.com> Message-ID: <1143853390.133464.36960@g10g2000cwb.googlegroups.com> Here's a wrapper for V4L. http://antonym.org/libfg From jstroud at ucla.edu Wed Mar 15 15:12:06 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 15 Mar 2006 12:12:06 -0800 Subject: best practices for making read-only attributes of an object In-Reply-To: <44186d15$0$31436$626a54ce@news.free.fr> References: <44186d15$0$31436$626a54ce@news.free.fr> Message-ID: bruno at modulix wrote: > Tim Chase wrote: >> >>class Foo: > > old-style classes are deprecated, please use new-style classes: > class Foo(object): > This should be re-phrased to 'Use new-style classes, or else!' py> class Foo: ... def __init__(self, color): ... self._color = color ... color = property(fget=lambda self: self._color) ... py> p = Foo('red') py> p.color 'red' py> p.color = 'green' # shouldn't be able to do this py> p.color 'green' py> py> class Parrot(object): ... def __init__(self, color): ... self._color = color ... color = property(fget=lambda self: self._color) ... py> p = Parrot('orange') py> p.color 'orange' py> p.color = 'pink' Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From scott.daniels at acm.org Sun Mar 19 11:54:25 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 19 Mar 2006 08:54:25 -0800 Subject: Unpythonic? Impossible?? In-Reply-To: <485ep5Fij70mU1@individual.net> References: <485ep5Fij70mU1@individual.net> Message-ID: <441d8a74$1@nntp0.pdx.net> BrJohan wrote: > Assume having this class hierarchy: (in principle and without details) > class A(object): > class B1(A): > class B2(A): > ... > each of those classes have an initializer __init__(self, data): and an > overloaded __new__(cls, data): > > is it then possible to have this call: > obj = A(data) > return an instance of that particular class (e.g. class C3) in the > hierarchy that - as decided by the __new__ functions - is the 'correct' one? > > A.__new__ could select between A, B1 and B2, while B1.__new__ could choose > from B1, C3 and C4. > > I know how to use a class factory - and could work around using such a > mechanism. However I am interested to know if I could let the classes do the > work by themselves. Yes, it can be done. Yes, it is unclear (and hence UnPythonic). The class factory _is_ the straightforward way to do this. The following is the workaround (if you have to maintain A(...)): class A(object): def __new__(class_, *args, **kwargs): if class_ is A: if want_a_B1(*args, **kwargs): return B1(*args, **kwargs) elif want_a_B2(*args, **kwargs): return B2(*args, **kwargs) return object.__new__(class_) # Use *a,... except for object class B1(A): def __new__(class_, *args, **kwargs): if class_ is B1: if want_a_B1(*args, **kwargs): return B1(*args, **kwargs) elif want_a_B2(*args, **kwargs): return B2(*args, **kwargs) return super(B1, class_).__new__(class_, *args, **kwargs) --Scott David Daniels scott.daniels at acm.org From fredrik at pythonware.com Sat Mar 18 05:35:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 18 Mar 2006 11:35:55 +0100 Subject: filter list fast References: <1142675680.468064.167930@v46g2000cwv.googlegroups.com> Message-ID: lars_woetmann wrote: > I have a list I filter using another list and I would like this to be > as fast as possible right now I do like this: > > [x for x in list1 if x not in list2] > > i tried using the method filter: > > filter(lambda x: x not in list2, list1) > > but it didn't make much difference, because of lambda I guess > is there any way I can speed this up if list2 is a list object, "not in list2" is an O(N) operation. maybe you should use sets instead ? does the following work better ? set2 = set(list2) result = [x for x in list1 if x not in set2] ? From rurpy at yahoo.com Thu Mar 30 18:44:10 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 30 Mar 2006 15:44:10 -0800 Subject: Doc suggestions (was: Why "class exceptions" are not deprecated?) In-Reply-To: References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com> <1143574346.354680.136060@i39g2000cwa.googlegroups.com> Message-ID: <1143762250.776248.235830@i40g2000cwc.googlegroups.com> "Terry Reedy" wrote: > wrote in message > news:1143574346.354680.136060 at i39g2000cwa.googlegroups.com... > > Fredrik Lundh wrote: > > But the perception I get here, from responses like yours, > > is that such suggestions are unwelcome, and unlikely > > to be acted upon. > > FL is not the main doc maintainer. Even if you were to be correct about > his views, premature generalization is the source of much error. Not sure how premature it is. I've been reading c.l.p. on and off for nearly a year. > > I gather corrections of factual > > errors are welcome, but stylistic, or organizational > > ones are not. And the latter kind of changes, applied > > extensively to all the docs, are what will make a big > > improvement. Difficult at best, but absolutely impossible > > if you and the other powers-that-be are happy with > > the status-quo. > > If you wish to become a volunteer Python improver, let me know either here > or privately and I will respond with a suggestion and an offer. Yes, please do. I'm sure it would be helpful, not only for me but for everyone dissatified with the current documentation and wanting to help, to hear your suggestion / offer. From mtebeka at qualcomm.com Mon Mar 6 07:38:48 2006 From: mtebeka at qualcomm.com (Miki Tebeka) Date: Mon, 06 Mar 2006 14:38:48 +0200 Subject: Popup menus without an associated window In-Reply-To: <1141628393.951985.250490@v46g2000cwv.googlegroups.com> References: <1141628393.951985.250490@v46g2000cwv.googlegroups.com> Message-ID: <440C2D58.3030709@qualcomm.com> Hello Rich, > Is there a way using any of the Python UI toolkits to generate popup > menus outside the context of an application? For example, > middle-clicking on the desktop shows a list of shortcuts to choose > from. > > Pointers to source examples would be appreciated. wxPython: import wx class Hidden(wx.Dialog): def __init__(self): wx.Dialog.__init__(self, None, -1) self.menu = wx.Menu() def add(title): item = self.menu.Append(-1, title) return item.GetId() self.ids = {} for title in ["One", "Two", "Three"]: self.ids[add(title)] = title self.Bind(wx.EVT_MENU, self.OnPopup) def Go(self): self.PopupMenu(self.menu) def OnPopup(self, evt): print "You selected %s" % (self.ids[evt.GetId()]) app = wx.PySimpleApp() dlg = Hidden() dlg.Go() dlg.Destroy() HTH, -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From nil at dev.nul Sat Mar 4 12:00:24 2006 From: nil at dev.nul (Christian Stapfer) Date: Sat, 4 Mar 2006 18:00:24 +0100 Subject: add an asynchronous exception class References: <7x3bhysotm.fsf_-_@ruckus.brouhaha.com> <7xu0aemyil.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xu0aemyil.fsf at ruckus.brouhaha.com... > "Fredrik Lundh" writes: >> PEP 348 addresses this by moving special exceptions out of the >> Exception hierarchy: >> >> http://www.python.org/peps/pep-0348.html > > I see that suggestion was rejected (it needed changing the semantics > of "except:"). Also, PEP 348 was rejected and is a huge, complex > reorganization of the whole exception system. This is cited: > > http://mail.python.org/pipermail/python-dev/2005-August/055423.html > > but it talks about distinguishing terminating from non-terminating > exceptions, whatever that means. (Won't any uncaught exception like > ValueError terminate the program)? I guess it means the following: "Terminating exceptions" are exceptions that terminate the *thrower* of the exception. "Non-terminating exceptions" are exceptions that might allow the thrower to resume (provided the catcher does *not* decide to unwind the thrower's stack frame - and possibly some other frames as well...). So non-terminating exceptions allow the thrower to offer the catcher a choice between terminating the thrower or having him try harder (until he possibly throws yet another, but maybe this time terminating exception that does not allow the catcher to ask for resumption of the throwing code). So what's terminated (or not terminated) here is not the program but merely the code that throws an exception. VAX/VMS had such a non-terminating exception handling mechanism, for example. Regards, Christian From duncan.booth at invalid.invalid Thu Mar 23 10:58:48 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Mar 2006 15:58:48 GMT Subject: Convert Word .doc to Acrobat .pdf files References: <1143123734.158567.97310@i39g2000cwa.googlegroups.com> <1143128817.437615.305860@u72g2000cwu.googlegroups.com> Message-ID: kbperry wrote: > Thanks for the replys! > > I need to stick with Word (not my choice, but I would rather keep > everything like he has it). That shouldn't be a problem: you can use stick with Word for editing the documents and just use OpenOffice to do the conversion. > > Duncan, > I was just trying the printing thing. When installing Adobe Acrobat, > it installs a printer called "Adobe PDF," and I have been trying to > print to there, but the "Save" window keeps popping up. I need to > figure out a way to keep it in the background. > I'm afraid its a while since I used Acrobat to generate PDF files. I think there are configuration options to tell it to do the conversion automatically and not prompt you, but I can't remember where. From rtilley at vt.edu Thu Mar 9 12:04:16 2006 From: rtilley at vt.edu (rtilley) Date: Thu, 09 Mar 2006 12:04:16 -0500 Subject: Python Evangelism In-Reply-To: <1141922861.541970.283350@j33g2000cwa.googlegroups.com> References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> <1141922861.541970.283350@j33g2000cwa.googlegroups.com> Message-ID: Paul Boddie wrote: > I agree with you here, though. I want to be diplomatic here, but Cheese > Shop - a name for a package repository, for those who are lost already > - is really just a totally stupid name. Yes, I'm aware of the Monty > Python sketch, mediocre by the high standards of the Pythons' various > other works, but people really shouldn't have to buy into some kind of > clique to decode terminology in order to get help, support, updates, > and to learn more about the technology they're using. Some people > haven't even seen Monty Python... Even more reason to change the name. Use a name that has lots of other widely known, well thought of names associated with it. The Ruby name is a very good example of this. Although, this was accidental and not planned. People associate the words precious, valued, gem, treasured, stone solid, etc. with the word ruby. Also, a good product with a good name makes it easy for others to add value by building other good names around it. What do you think of when you hear 'eggs'? Many people think 'rotten', 'smelly' or something that made them throw-up once. The point of this is that names _matter_ and influence what others think even if only in a subconscious way. I'll leave it at that. I like Python a lot. Technically, it's awesome. I don't think the language is bad... just the names associated with it. Just my 2 cents. From http Thu Mar 9 22:18:55 2006 From: http (Paul Rubin) Date: 09 Mar 2006 19:18:55 -0800 Subject: Password entering system References: <1141960578.121787.205690@i39g2000cwa.googlegroups.com> Message-ID: <7xslprt2ao.fsf@ruckus.brouhaha.com> "Tuvas" writes: > I want to write a GUI program (Preferably in Tkinter) that will allow > for the entering of passwords, stared out like a normal program does. > Is that possible? Thanks! http://blogs.translucentcode.org/oisin/2003/09/04/tkinter_password_entry/ From rod at sudden.net Thu Mar 2 19:46:47 2006 From: rod at sudden.net (Sudden Disruption) Date: 2 Mar 2006 16:46:47 -0800 Subject: how do you move to a new line in your text editor? In-Reply-To: <%ZGNf.1711$No6.40016@news.tufts.edu> References: <%ZGNf.1711$No6.40016@news.tufts.edu> Message-ID: <1141346807.520450.28740@z34g2000cwc.googlegroups.com> John, > This is a real small point No point is small when you apply it hundreds of times a day. I spent quite a bit of time on this element and ended up allowing conversion from tabs to spaces and the reverse. Who knows what you'll find in the world of ASCII. Historically, Tabs were stops on the typewriter carriage, a control function. This Tabs = Spaces thing came about largely because of cursor bondage. So how do YOU think of a Tab key? Is it a data key or a control key? Internally, I treat Tab (and Shift Tab) as a navigation (control) key instead of pumping in lots of spaces. It seems more useful that way. But then Sudden View doesn't have "cursor bondage" to worry about. Sudden Disruption Try Sudden View - for the art of editing text Beta test now in progress at... http://www.sudden.net/ From phpbird at gmail.com Thu Mar 16 09:06:48 2006 From: phpbird at gmail.com (JuHui) Date: 16 Mar 2006 06:06:48 -0800 Subject: can httplib.HTTPConnection use proxy? In-Reply-To: References: <1142498251.768992.158040@i39g2000cwa.googlegroups.com> Message-ID: <1142518008.208091.73950@j33g2000cwa.googlegroups.com> sorry, would you please give a sample code? I want to use HTTPConnection to get a html page content via a http proxy. thanks. From n.estner at gmx.de Fri Mar 24 16:39:08 2006 From: n.estner at gmx.de (nikie) Date: 24 Mar 2006 13:39:08 -0800 Subject: Linear regression in NumPy References: <1142628938.982098.239850@u72g2000cwu.googlegroups.com> <1142631926.353064.206010@p10g2000cwp.googlegroups.com> <1142639157.977175.257900@u72g2000cwu.googlegroups.com> <%PVSf.52$Qm2.24@trndny03> <1142698211.185324.154130@j33g2000cwa.googlegroups.com> <1143110807.307714.320840@u72g2000cwu.googlegroups.com> <1143198706.448457.24920@e56g2000cwe.googlegroups.com> Message-ID: <1143236348.914449.137750@v46g2000cwv.googlegroups.com> > The version I have in front of me is a bit shorter, 252 pages, but describes > polyfit in section 5.3 on page 91 along with the other polynomial functions. > lstsq (linear_least_squares is a backwards-compatibility alias that was recently > moved to numpy.linalg.old) is described in section 10.1 on page 149. Oops, sorry, shouldn't have posted before reading the whole document... You are right, of course, both functions are explained. I wonder why the acrobat's search function doesn't work, though. From dw at botanicus.net Sat Mar 11 19:25:59 2006 From: dw at botanicus.net (David Wilson) Date: 11 Mar 2006 16:25:59 -0800 Subject: IOS-style command line interface module? Message-ID: <1142123159.212193.21400@u72g2000cwu.googlegroups.com> Hi folks, I seem to remember seeing a module some time in the distant past that provided an API for implementing Cisco IOS-like command line interfaces. I can't for the life of me find a reference to it on Google now. Does anyone know what I'm talking about? Thanks, David. From fumana at lambrate.inaf.it Fri Mar 10 03:19:29 2006 From: fumana at lambrate.inaf.it (fumana at lambrate.inaf.it) Date: Fri, 10 Mar 2006 09:19:29 +0100 Subject: API/C memory mananegemnt problem Message-ID: <200603100919.29946.fumana@mi.iasf.cnr.it> Hi everybody, I have a problem with Python/C API and memory management. I'm using Python 2.3.5 (#1, Jan 4 2006, 16:44:27) [GCC 4.0.2 20050901 (prerelease) (SUSE Linux)] on linux2 In my C-module I have a loop like this: *********************************************** int size=10000000; output=(double *) calloc(size, sizeof(double)); py_output=PyList_New(0); for(i=0; i References: <7g1p12ttfcf1sd5v9rrggr6ioushs2e1id@4ax.com> Message-ID: Dennis Lee Bieber wrote: > On Sat, 18 Mar 2006 17:24:05 -0500, Kevin F > declaimed the following in comp.lang.python: > >> I fixed the indentation to: >> >> emails = [] >> for msg in messagesInfo: >> msgNum = int(split(msg, " ")[0] >> msgSize = int(split(msg, " ")[1] > > Now look at your parentheses... >> and it still doesn't work, what's wrong? > >> msgNum = int(split(msg, " ")[0] > HINT: 0 1 2 1 ? i have no idea what you are hinting at, can you please just tell me what i need to change? From grante at visi.com Thu Mar 23 10:09:18 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 23 Mar 2006 15:09:18 -0000 Subject: removing file by inode References: <1143090399.430131.224390@t31g2000cwb.googlegroups.com> Message-ID: <1225egub5k1kv3b@corp.supernews.com> On 2006-03-23, s99999999s2003 at yahoo.com wrote: > is it possible to remove a file by it's inode and not it's filename > using Python? What do you mean "remove a file"? -- Grant Edwards grante Yow! Life is a POPULARITY at CONTEST! I'm REFRESHINGLY visi.com CANDID!! From onurb at xiludom.gro Thu Mar 30 09:50:47 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 30 Mar 2006 16:50:47 +0200 Subject: How to determine an object is "scriptable" In-Reply-To: References: <1143726903.153135.317880@j33g2000cwa.googlegroups.com> Message-ID: <442bf088$0$13222$626a54ce@news.free.fr> Larry Bates wrote: > abcd wrote: > >>I recently came across a problem where I saw this error: >>"TypeError: unsubscriptable object" >> >>How can I determine if an object is "scriptable" or "unscriptable"? >> > > Simplest answer is to use isinstance to see if it is a string, list, > or tuple: > > if isinstance(variable, (str, list, tuple)): Which will fail for a whole lot of objects that are scriptable... Better use Daniel's solution or a try/except. > > Now the problem is that this answer doesn't address the problem. > Your code is attempting to do something to the wrong type of > object/variable which is a logic problem. Of course !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From aleaxit at yahoo.com Thu Mar 9 01:43:42 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Mar 2006 22:43:42 -0800 Subject: PyGUI 1.6: A Note for MacOSX Users References: <46ks6sFb488qU1@individual.net> <1hbiedq.15e14ng9jykarN%aleaxit@yahoo.com> <440FA643.2020700@cosc.canterbury.ac.nz> Message-ID: <1hbwkfg.1hen5zp1s92vavN%aleaxit@yahoo.com> Greg Ewing wrote: > Alex Martelli wrote: > > > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-pa > > ckages/GUI/Cocoa/Applications.py", line 184, in init_application_name > > ns_info['CFBundleName'] = GApplications.application_name > > TypeError: object does not support item assignment > > You need to run your program with pythonw, not python. Thanks -- that was indeed my mistake. Dunno why I keep tripping over that problem on the Mac;-). Alex From tdwdotnet at gmail.com Thu Mar 23 11:43:16 2006 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Thu, 23 Mar 2006 16:43:16 +0000 Subject: raw_input In-Reply-To: References: Message-ID: <9afea2ac0603230843u77ea30efv@mail.gmail.com> On 23/03/06, cm012b5105 wrote: > > > > > > if s = raw_input ("hello what's your name? ") > if s=='carmel ': > print "Ahh the boss's wife" > > > > What i would like to know is what if she doesn't write carmel she rights > say carm short of me writing if s=='carm': on a new line is there a > shorter way of doing this so i can cover all angles on how she might write > her name. > Thanks nigeps I appologise for my earlier thread > > if she doesn't write carmel she rights say carm The following will accept any subset of "carmel" in upper, lower or mixed case EG Carmel, carmel, Carm, mel etc >>> if raw_input ("hello what's your name? ").lower() in 'carmel': ... print "Ahh the boss's wife" -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue Mar 14 12:26:51 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 14 Mar 2006 18:26:51 +0100 Subject: Tried Ruby (or, "what Python *really* needs" or "perldoc!") References: <1142355126.757569.42160@i40g2000cwc.googlegroups.com> <47obg1Fgjd6kU1@uni-berlin.de> <1142357107.619114.180650@i40g2000cwc.googlegroups.com> Message-ID: <47ocnkFgihgsU1@uni-berlin.de> > Thanks Diez! Epydoc looks great. > > Can we use epytext to generate output suitable for a manpage? Don't know, never tried that. > Do you prefer epytext or reST? So far epytext suited my needs. Diez From adam.deprince at gmail.com Sun Mar 26 11:42:11 2006 From: adam.deprince at gmail.com (Adam DePrince) Date: Sun, 26 Mar 2006 11:42:11 -0500 Subject: Extending Methods Vs Delegates In-Reply-To: <1hcsoo8.16314r0vrnqpiN%aleaxit@yahoo.com> References: <1142985431.079078.3480@i40g2000cwc.googlegroups.com> <1hckjdk.c55h629l2oz8N%aleaxit@yahoo.com> <1143370158.058148.180170@v46g2000cwv.googlegroups.com> <1hcsoo8.16314r0vrnqpiN%aleaxit@yahoo.com> Message-ID: <1143391331.3426.62.camel@localhost.localdomain> On Sun, 2006-03-26 at 07:21 -0800, Alex Martelli wrote: > vbgunz wrote: > > > I am sorry I couldn't reply sooner! Alex, Python in a nutshell is my > > bible and I take it virtually everywhere! Seriously, I would highly > > recommend it to anyone with a little to a lot of Python experience. > > > > I apologize for misinterpreting your passage on page 80. I will look > > much closer at your examples, links and ideas and I hope to straighten > > my knowledge on the subject of delegates! > > > > Thank you for hinting on the "Template Method design pattern"! Sorry > > for any misunderstanding! > > Hey, no problem -- such a misunderstanding is always a shared > responsibility, and as an author I need to take my part of the blame. > > Unfortunately, the root issue is that more and more common, ordinary, > useful English words get expropriated by specialized technical meanings, > making it almost impossible to discuss technical matters in ordinary > English without *some* risk of misunderstanding (by the reader > mistakenly seeing a "specialized, technical meaning" where the NORMAL > English use of the word, possibly in a slightly metaphorical vein, is > what the author meant). From "function" and "procedure", to "delegate" > and "built-in", a growing number of words become "risky"!-) > > Funny enough, the problem is worst in English - because in many other > languages, the specialized technical terms often use borrowed English > words, so the other language's native terms remain available. Latin had > similar luck wrt Greek a couple millennia ago -- all technical terms of > philosophy were borrowed Greek words, so the risk of confusion was in > fact much lower than it was in Greek;-). Of course, any language suffers that problem when the rise of a new field is associated with it. Medicine draws from Latin. For English speakers that is wonderful, a whole language from which to assign specific meanings. But consider Mr. DaVinci at one of his past-times, the dissection of rapidly decomposing corpses for the secrets hidden within. That he might choose to spell his description of the inside of an eye as vitreous humor, instead of say, eye slime, didn't make it sound as impressive to him as the term does to me today. I almost feel that a true appreciation for the complexity of any endeavor must wait until its native language passed a bit from the spot light. While I can't speak for other fields, I believe that our "linguistic address space" does limit our progress. Take list interpolations for instance ... interpolation has other, specific meanings in other not so far removed fields. When I first read about it, I had to backup and think for a moment, if only to resolve the fact that yet another term is overloaded. And even our keyboards limit our space. I can create a tuple (), or a list [], or a dict{}, but why can't I create another structure .. oh wait, we are out of parenthesis like characters, and nobody has the courage to recycle the of HTML fame <> pair. Now, as I work on my mutable sequences PEP and implementation, I find myself annoyed without a good, non-overloaded, way of naming an iter friendly variant of a data store's normal __delitem__. Actually, this wasn't more than a minute long problem, but the rate of collisions within the English word space is a problem. At least English is pretty friendly about adopted and synthetic words. Cheers - Adam From benwbrewster at gmail.com Fri Mar 31 16:31:38 2006 From: benwbrewster at gmail.com (benwbrewster at gmail.com) Date: 31 Mar 2006 13:31:38 -0800 Subject: best way to index numerical data ? In-Reply-To: <1143832404.390434.280360@t31g2000cwb.googlegroups.com> References: <1143822878.075138.285760@g10g2000cwb.googlegroups.com> <1143832404.390434.280360@t31g2000cwb.googlegroups.com> Message-ID: <1143840698.517704.319990@i40g2000cwc.googlegroups.com> here is a sample of a .txt file : I want to search for the whole number. If possible, fuzzy search would be nice too, but not mandatory.. 1975|Y|35136|72|1927|||3|005503|003|19870301|19950301|14416887|151|20000301|100039292|N|84|F|50||10|A|100|Y|037|Y|89005|3042|M|S|P| Thanks! Jack From kent at kentsjohnson.com Mon Mar 13 16:10:56 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 13 Mar 2006 16:10:56 -0500 Subject: Is this possible in Python? In-Reply-To: <1142282467.270698.142780@p10g2000cwp.googlegroups.com> References: <1142238871.199749.243470@p10g2000cwp.googlegroups.com> <1142282467.270698.142780@p10g2000cwp.googlegroups.com> Message-ID: <4415daf9$1_3@newspeer2.tds.net> alainpoint at yahoo.fr wrote: > Hello again, > I am disappointed. You are the experts, you've got to try harder ;-) > What i want is a generalisation of this tiny function: Why? Maybe we can find a better way... Kent From jimlewis at miclog.com Sat Mar 4 18:53:27 2006 From: jimlewis at miclog.com (swisscheese) Date: 4 Mar 2006 15:53:27 -0800 Subject: Passing a method indirectly Message-ID: <1141516407.480315.22400@e56g2000cwe.googlegroups.com> I'm trying to write a function that takes an arbitrary object and method. The function applies the method to the object (and some other stuff). I get error "Test instance has no attribute 'method' " How can I make this work? def ObjApply (object,method): object.method () class Test: def test1 (self): print "Hello" def test2 (self): ObjApply (self,self.test1) ta = Test () ta.test2 () From totalgeekdom at gmail.com Mon Mar 20 16:35:24 2006 From: totalgeekdom at gmail.com (totalgeekdom at gmail.com) Date: 20 Mar 2006 13:35:24 -0800 Subject: System Information In-Reply-To: <1142818948.683763.288360@i39g2000cwa.googlegroups.com> References: <1142814987.299021.7380@i39g2000cwa.googlegroups.com> <1142818107.594919.298370@g10g2000cwb.googlegroups.com> <1142818948.683763.288360@i39g2000cwa.googlegroups.com> Message-ID: <1142890524.870468.220980@j33g2000cwa.googlegroups.com> Good news! I asked a buddy that runs osx, and he whipped up a script for you :) I understand it's not python, but it gets you close, you should be able to use popen or subprocess.call to complete this. function is_charger_plugged_in() { sleep 3; BATTINFO=`ioreg -l -w 0 | grep IOBatteryInfo | head -n 1 | sed -e 's/[( ) { }]//g'` AMP=`echo $BATTINFO | awk -F, '{print $2}' | cut -f 2 -d =` CAP=`echo $BATTINFO | awk -F, '{print $7}' | cut -f 2 -d =` if [ "$AMP" -lt "$CAP" ]; then return 0 else return 1 fi > /dev/null 2>&1 } is_charger_plugged_in if [ "$?" -eq "0" ]; then echo "charger is plugged in"; else echo "charger is not plugged in"; fi If I had to guess for the python script I'd do -- #!/usr/bin/env python import time,os def pluggedin(): # ioreg is for osx only time.sleep(3) battInfo = "ioreg -l -w 0 | grep IOBatteryInfo | head -n 1 | sed -e 's/[( ) { }]//g'" amp = "echo $BATTINFO | awk -F, '{print $2}' | cut -f 2 -d =" cap = "echo $BATTINFO | awk -F, '{print $7}' | cut -f 2 -d =" if amp < cap: return 0 else: return 1 if pluggedin() == 1: print "It is plugged in" else: print "It is not plugged in" Original code was hooked up to me by prism =) Cause he's a cool guy Hope that helps! From kent at kentsjohnson.com Tue Mar 21 14:06:09 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 21 Mar 2006 14:06:09 -0500 Subject: Installing PyExcelerator to write Excel files from Python In-Reply-To: <1142963278.278651.99160@t31g2000cwb.googlegroups.com> References: <1142963278.278651.99160@t31g2000cwb.googlegroups.com> Message-ID: <44204991_2@newspeer2.tds.net> tkpmep at hotmail.com wrote: > I downloaded PyExcelerator.zip as I need to write some data into Excel > files, and tried unsuccessfully to install it. I unzipped the files > into C:/Python24/Lib/site-packages/PyExcelerator You should unzip to somewhere else, the install step will put the correct files into site-packages. Kent From doug at localhost.localdomain Wed Mar 15 07:46:07 2006 From: doug at localhost.localdomain (Doug) Date: Wed, 15 Mar 2006 12:46:07 GMT Subject: libglade for python-2 Message-ID: I am having some fun running a program called pygps. This uses libglade and runs fine on my very old Redhat 7.? system running Python 1.5.2. I have not needed to make any changes to the import files (see below). The program uses a glade generated pygps.glade xml file for the gui. I like the way this works and the ability to edit the xml(?) with glade. Now on my Fedora system which has version 2 of just about everything it will not run and I cannot figure how to get the code to work. The site packages include a glade.so file but there is no libglade. Googling I have not found specifc support for libglade in anything other than ada and c, nothing for python 2.0. Is there a mechanism to invoke libglade operation (ie a separate xml file generated by glade-2 like I have with the old python 1 system? Note that I have discovered the older glade files are not compatible with glade-2. Is libglade dead now for python-2 or am I missing something? See: http://pygps.org/ Imports from pygps: import GDK from gtk import * import math import socket, string import libglade import GdkImlib import os from LatLongUTMconversion import LLtoUTM import NMEA (Ignore the last two, they are local but I have included them for completeness) Doug From ask at me Fri Mar 24 09:23:21 2006 From: ask at me (AndyL) Date: Fri, 24 Mar 2006 09:23:21 -0500 Subject: path to modules per import statement In-Reply-To: <1143127952.665765.155950@j33g2000cwa.googlegroups.com> References: <1143127952.665765.155950@j33g2000cwa.googlegroups.com> Message-ID: danmcleran at yahoo.com wrote: >>For instance: "import my.path.module" would load module from >>./my/path/module.py? > > > Yeah, just do that. I don't understand the question, it works just like > this today. > I work on rather big set of Python applications: something like 100 .py files divided into libs and separate sub-applications. For now I keep almost everything in one directory but I wish following structure to be in place: app1/ app2/ lib1/ lib2/ lib3/ and be able to import from each app[12] all the libs. I do not want to touch existing code to prefix all the import places with lib[123] nether I want to play with sys.path.append too much. A. From robert.kern at gmail.com Fri Mar 17 18:58:23 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 17 Mar 2006 17:58:23 -0600 Subject: Linear regression in NumPy In-Reply-To: <1142639157.977175.257900@u72g2000cwu.googlegroups.com> References: <1142628938.982098.239850@u72g2000cwu.googlegroups.com> <1142631926.353064.206010@p10g2000cwp.googlegroups.com> <1142639157.977175.257900@u72g2000cwu.googlegroups.com> Message-ID: nikie wrote: > I still don't get it... > My data looks like this: > x = [0,1,2,3] > y = [1,3,5,7] > The expected output would be something like (2, 1), as y[i] = x[i]*2+1 > > (An image sometimes says more than 1000 words, so to make myself clear: > this is what I want to do: > http://www.statistics4u.info/fundstat_eng/cc_regression.html) > > So, how am I to fill these matrices? As the docstring says, the problem it solves is min ||A*x - b||_2. In order to get it to solve your problem, you need to cast it into this matrix form. This is out of scope for the docstring, but most introductory statistics or linear algebra texts will cover this. In [201]: x = array([0., 1, 2, 3]) In [202]: y = array([1., 3, 5, 7]) In [203]: A = ones((len(y), 2), dtype=float) In [204]: A[:,0] = x In [205]: from numpy import linalg In [206]: linalg.lstsq(A, y) Out[206]: (array([ 2., 1.]), array([ 1.64987674e-30]), 2, array([ 4.10003045, 1.09075677])) -- Robert Kern robert.kern at gmail.com "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 alejandro.weinstein at gmail.com Tue Mar 28 15:45:47 2006 From: alejandro.weinstein at gmail.com (Alejandro) Date: 28 Mar 2006 12:45:47 -0800 Subject: pySerial: write in a blocking mode Message-ID: <1143578747.023574.150300@i39g2000cwa.googlegroups.com> Hi: I'm using pySerial to talk to a RS232 to RS485 converter. In order to control the converter, I need to control the DTR line to enable/disable de RS485 driver. In particular, I need to : write a character to the serial port set the DTR line to level 1 _after_ the last bit of the character is send So I tried this (ser is the serial port object): ser.write(x) ser.setDTR(1) The problem with this is that the ser.write function returns before the character is send, and thus, the DTR line is set too soon. (I checked this behaivour with an osciloscope). I thought that seting the writeTimeout parameter could help, but then I realized that the write function wait "up to this time", so it doesn't work. Then I tried waiting some time with time.sleep() after ser.write, but the shortest time for time.sleep is to big, and non deterministic, so I think this is not an option. Does anybody know how to do a ser.write() in a blocking way? Regards, Alejandro. From pmartin at snakecard.com Mon Mar 27 07:45:21 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Mon, 27 Mar 2006 06:45:21 -0600 Subject: PIL & image size reduction script References: <1143419780.383974.88180@t31g2000cwb.googlegroups.com> Message-ID: PS: where can I find those extra parameters in the doc (ex: quality) ... I must be blind. Philippe nikie wrote: > Philippe Martin wrote: >> Hi, >> >> Thanks to the NG, I got the script hereunder working. >> >> 1) I am not certain that the call to convert does much (checking the doc) > > I think you only need it if your source image comes in a format that > can't be stored into a jpeg file (e.g. 8-bit paletted). You'll need > that if you're converting from GIF files, for example. It shouldn't > hurt otherwise. > >> 2) Can this be improved as far as the final image size in (X,Y) ? > > I'm not sure if I get you: You tell the image object it's new > (X,Y)-size in the resize method, don't you? > >> For instance, passing a large .jpg with a target byte size of 7000, I get >> final (X,Y) results around (213, 174) ... but might want to strech it a >> bit while keeping the byte size. > > If I got you right, you want to compress the image to a certain file > size. Maybe you should try optimizing the additional save parameters > for the jpeg encoder. > (http://www.pythonware.com/library/pil/handbook/formats.htm). Try > reducing the "quality" parameter. > l_image.save(l_tmp_file_name, quality=25) > > Hope this helps. > > Niki From tim.leeuwvander at nl.unisys.com Fri Mar 24 03:48:48 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 24 Mar 2006 00:48:48 -0800 Subject: Bitwise OR? In-Reply-To: <1143187977.384459.225840@i40g2000cwc.googlegroups.com> References: <1143187977.384459.225840@i40g2000cwc.googlegroups.com> Message-ID: <1143190128.783253.62430@i40g2000cwc.googlegroups.com> Actually, following up to my own reply: 3500 | 67 = 3567. So perhaps that sets your expectations for 3500 | -67. But try -3500 | -67 for fun: it is -3 Bitwise or is no arithmetic and if you want to predict something about the resulting integers, you should know something about how they are stored. Negative integers are stored in 2-complement format: minus 1 is all bits set to 1. Turning bits off makes it a more negative number (as long as you don't touch the sign-bit) and turning more bits on makes it a smaller negative number. Doing bitwise-OR for the positive numbers 3500 and 67 results in 3567: proof that they don't have any overlapping bits. Know it turns out that 3500 and -67 have only overlapping bits: therefore the result is -67. (adding the bits from 3500 to the bits of -67 doesn't turn on any extra bits). Use bit operators to manipulate bits, and think of the operands as sets of bits. Bitwise OR is the union of 2 sets of bits. Don't think of the operands to bit operators as numbers, and don't try to do your sums using bitwise or! :-) --Tim From hancock at anansispaceworks.com Thu Mar 2 00:04:16 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 1 Mar 2006 23:04:16 -0600 Subject: Suggestions for documentation generation? In-Reply-To: References: <1141240014.302680.78850@z34g2000cwc.googlegroups.com> Message-ID: <20060301230416.5170994e@samwise.anansi> On Wed, 01 Mar 2006 19:58:50 -0500 "John M. Gabriele" wrote: > kpd wrote: > > I have written a C++ library that I've then wrapped with > > Pyrex. Any suggestions to the best-in-class tool to > > create documentation for the libraries? > > > > I would love to document things in one spot (could be > > the code) and generate html and PDF from there. > > > > Doxygen (www.doxygen.org) looks to be about the best so > > far. > > I've heard that some folks use pythondoc: > http://starship.python.net/crew/danilo/pythondoc/ > http://effbot.org/zone/pythondoc.htm > > There's also HappyDoc http://happydoc.sourceforge.net/ > and EpyDoc http://epydoc.sourceforge.net/ . Those are great, but I don't think they handle C++ ;-) Which makes me wonder -- will epydoc work on a pyrex or C-extension file if it defines the __doc__ strings? -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From johnjsal at NOSPAMgmail.com Sun Mar 12 22:01:46 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 12 Mar 2006 22:01:46 -0500 Subject: how exactly do binary files work in python? In-Reply-To: <3aGdnZUhQZn-I4nZRVn-jw@speakeasy.net> References: <3aGdnZUhQZn-I4nZRVn-jw@speakeasy.net> Message-ID: Erik Max Francis wrote: > You can use the struct module for converting fundamental types to a > portable string representation for writing to binary files. But if it's a string, why not just use a text file? What does a binary file do that a text file doesn't, aside from not converting the end of line characters? From cdkrug at aol.com Sun Mar 26 17:36:43 2006 From: cdkrug at aol.com (Charles Krug) Date: Sun, 26 Mar 2006 16:36:43 -0600 Subject: What's The Best Editor for python References: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> <1143342423.569443.188800@j33g2000cwa.googlegroups.com> Message-ID: On 2006-03-26, Andrew Gwozdziewycz wrote: > If you want something that won't get in your way, you should really > use /bin/ed. It's probably simpler to use then searching the archives. > /bin/ed will also run in cygwin for windows. > >>> Can one of you say to me what's the best editor for >>> editing the python programs( for linux or windows ) > The best editor is the one you like best. I'm a vim user with taglist--I'm not fully happy with how ctags does Python, but it's more than Good Enough. But editors are religious, and not worth arguing about, generally. From reply.in.the.newsgroup at my.address.is.invalid Tue Mar 21 19:57:41 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 22 Mar 2006 01:57:41 +0100 Subject: TaskQueue References: <1142937223.607170.7160@v46g2000cwv.googlegroups.com> <1142950069.015915.38320@v46g2000cwv.googlegroups.com> <1142987034.195619.230850@i39g2000cwa.googlegroups.com> Message-ID: Carl Banks: >Rene Pijlman: >> Ah yes, clever trick. But you'd have to worry about thread-safety of your >> subclass though. > >Queue worries about this for you. The Queue class only calls _get when >it has the queue's mutex, so you can assume thread safety when >subclassing it. Ah yes, I overlooked the underscore. But you'd have to worry about everything get() is doing before it calls _get() though :-) >Say you were writing a FiniteQueue class that implemented the permament >sentinel trick to indicate to all consumer threads that the queue is >done. For your own code, you may know that you'll never need to pass >None through the queue, but you can't assume that for all code. Ah, this is where assert proves its value. class FiniteQueue(object): def putTask(self,task): assert task is not None self.workQueue.put(task) self.numberOfTasks += 1 # ... -- Ren? Pijlman Wat wil jij leren? http://www.leren.nl From aisaac0 at verizon.net Sat Mar 25 10:31:33 2006 From: aisaac0 at verizon.net (David Isaac) Date: Sat, 25 Mar 2006 15:31:33 GMT Subject: __slots__ References: <1143106365.996810.269780@z34g2000cwc.googlegroups.com> Message-ID: "Aahz" wrote in message news:e0195k$5j5$1 at panix3.panix.com... > Because __slots__ breaks with inheritance. I believe that was the point of Ziga's example, which I acknowledged as a good one in my reply. So there still appears to be this single reason, which applies if your class may be subclassed. Does this beg the question of whether __slots__ *should* break with inheritance? One other question I did not get answered: is there any simple example of a Pythonic use of __slots__ that does NOT involve the creation of **many** instances. Thanks, Alan Isaac From abhimanyu.seth at gmail.com Tue Mar 7 01:50:37 2006 From: abhimanyu.seth at gmail.com (Abhimanyu Seth) Date: Tue, 7 Mar 2006 12:20:37 +0530 Subject: minidom and unicode errors In-Reply-To: References: <591d95910603062133t1a549115jebf207ede0d86010@mail.gmail.com> <591d95910603062221m64169965wbf9b99dbb4072f4e@mail.gmail.com> Message-ID: <591d95910603062250l2fa52c21yf59c346c5a4e6937@mail.gmail.com> On 3/7/06, Fredrik Lundh wrote: > > Abhimanyu Seth wrote: > > > > I have the following line in my xml file: > > > Exception beim L?schen des Audit-Moduls aufgetreten. Exception > > Stack > > > lautet: %1. > > > ExpatError: not well-formed (invalid token): line 8, column 27 > > > I've specified utf-8 in the xml header > > > > are you sure you're using utf-8 in the XML file? the ? you pasted into > your mail is an iso-8859-1 code, not an utf-8 code. > > > Anyway, > > >> f = codecs.open ("c:/test.txt", "r", "latin-1") > > >> dom = minidom.parseString (codecs.encode (f.read(), "utf-8")) > > works. > > which means that you've labelled the file as utf-8, but that it actually > contains iso-8859-1. fixing the file should fix this. > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > Sorry, my mistake. The file was not saved as utf-8. Saving it as utf-8 solves my problems. >> f = codecs.open ("c:/test.txt", "r", "utf-8") >> dom = minidom.parseString (codecs.encode (f.read(), "utf-8")) However, I still need to encode the string returned by f.read () before passing it to parseString. Otherwise I get an exception. Thanks, anyway for all the help. -- Regards, Abhimanyu -------------- next part -------------- An HTML attachment was scrubbed... URL: From bronger at physik.rwth-aachen.de Mon Mar 6 11:49:04 2006 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 06 Mar 2006 17:49:04 +0100 Subject: Why I chose Python over Ruby References: <1141573450.667103.8930@z34g2000cwc.googlegroups.com> <874q2bpv5q.fsf@wilson.homeunix.com> Message-ID: <874q2bmscf.fsf@wilson.homeunix.com> Hall?chen! Xavier Morel writes: > Torsten Bronger wrote: > >> Yes, however, this is also true for Python in my opinion. > > Ruby's ability to generate DSLs is an order of magnitude better > than Python's at least. If good DSL includes morphing into another language, this may be true. However, I think that a good DSL just solves the problem well, even if it still looks like the original by and large. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus ICQ 264-296-646 From jacob.kroon at gmail.com Fri Mar 10 13:17:57 2006 From: jacob.kroon at gmail.com (Jacob Kroon) Date: Fri, 10 Mar 2006 19:17:57 +0100 Subject: Python cleanup on exit Message-ID: <4411C2D5.7010407@gmail.com> Hi, I'm working on a library written in C using GObject, which i provide python bindings for using pygtk. When I checked the library for memory leaks using valgrind, I noticed that none of the objects I created in the script (that is they are global in the script) were deleted on exit. After some googling I came to the conslusion that the python interpreter doesn't "cleanup" after itself on exit, because of shutdown performance. This means that if I want to check the library for mem leaks I have to either manually "del myobject1, delmyobject2 ..." at the end of the scripts, or make sure that all objects get created in a function scope, so that python will delete them for me when the interpreter exits the scope. Is there another way to make python delete objects which were created in the global scope upon exit ? Jacob From aisaac0 at verizon.net Sun Mar 26 04:32:31 2006 From: aisaac0 at verizon.net (David Isaac) Date: Sun, 26 Mar 2006 09:32:31 GMT Subject: Comparisons and singletons References: <1143283477.483035.212980@v46g2000cwv.googlegroups.com> <1143306711.041441.43470@i40g2000cwc.googlegroups.com> Message-ID: Alan asked: > > 2. If I really want a value True will I ever go astray with the test: > > if a is True: > > >>> a = True > > >>> b = 1. > > >>> c = 1 > > >>> a is True, b is True, c is True > > (True, False, False) "Ziga Seilnacht" wrote in message news:1143306711.041441.43470 at i40g2000cwc.googlegroups.com... > I think that True and False, although they were added in version > 2.3, were not true singeltons until version 2.4. OK, but Python 2.3 yields the same result as above. Ziga wrote: > You should finish > reading the PEP, see especially this part: > - Don't compare boolean values to True or False using == > Yes: if greeting: > No: if greeting == True: > Worse: if greeting is True: I do not think this is relevant to the question I asked, which was how to test for a value of True, if that's what I really want. I think the outcome of this discussion has been: use 'is'. Thanks, Alan From nkammah at yahoo.fr Tue Mar 7 19:48:11 2006 From: nkammah at yahoo.fr (kepioo) Date: 7 Mar 2006 16:48:11 -0800 Subject: SAX/Python : read an xml from the end to the top In-Reply-To: References: <1141699735.555057.324540@p10g2000cwp.googlegroups.com> <474v65Fdv6vfU1@uni-berlin.de> <1141732681.385933.178960@v46g2000cwv.googlegroups.com> <1141743297.597655.261010@v46g2000cwv.googlegroups.com> Message-ID: <1141778891.472758.75560@j33g2000cwa.googlegroups.com> An example ( i changed the content to make it easier) : ################### input file ####################3 fruits 5 10 25 names vincent Robert open the car fruits 25 8 120 ##############################################3 The script I want to write has to track any change in the input file(what we want to track are parameters in the script. Here for instance, the number of apple and cherry). The ouput file for this example would be ( we write it as a stream): ################### OutPut file ################################# fruits 5 fruits 8 fruits 120 ############################################33333 The input file keeps being generated. The ouput file is generated on request. Both are streamed based : we happend to the end of the file. From scott.daniels at acm.org Thu Mar 9 09:34:58 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 09 Mar 2006 06:34:58 -0800 Subject: encoding problem In-Reply-To: References: <440827D6.3060501@sitasoftware.lu> Message-ID: <44103b0e$1@nntp0.pdx.net> Yves Glodt wrote: > It seems in general I have trouble with special characters... > What is the python way to deal with ??? ??? etc... > > print '?' fails here, This should probably stay true. > print u'?' as well :-( This is an issue with how your output is connected. What OS, what code page, what application? I'm using Win2K, Python 2.4.2 Using Idle, I can do: print u'?l?ve' And get what I expect I can also do: print repr(u'?l?ve') which gives me: u'\xe9l\xe8ve' and: print u'\xe9l\xe8ve' Also shows me ?l?ve. With cmd.exe (the command line): c:\ python >>> print u'\xe9l\xe8ve' shows me ?l?ve, but I can't type in: >>> print u'lve' is what I get when I paste in the print u'?l?ve' (beeps during paste). What do you get if you put in: >>> print repr('?l?ve') --Scott David Daniels scott.daniels at acm.org From tomasz.zielonka at gmail.com Thu Mar 16 09:57:31 2006 From: tomasz.zielonka at gmail.com (Tomasz Zielonka) Date: Thu, 16 Mar 2006 14:57:31 +0000 (UTC) Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> Message-ID: Major correction (missing case): Tomasz Zielonka wrote: > generateMatching :: (Ord a) => Int -> Set a -> [Pat a] -> [[a]] > generateMatching 0 _ [] = [[]] generateMatching 0 alphabet (All:ps) = generateMatching 0 alphabet ps > generateMatching 0 _ (_:_) = [] Best regards Tomasz -- I am searching for programmers who are good at least in (Haskell || ML) && (Linux || FreeBSD || math) for work in Warsaw, Poland From jparlar at cogeco.ca Tue Mar 7 22:10:29 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Tue, 7 Mar 2006 19:10:29 -0800 Subject: Type Hinting vs Type Checking and Preconditions In-Reply-To: References: Message-ID: On Mar 7, 2006, at 1:32 PM, Tom Bradford wrote: > > Let me first say that I'm sure that this subject has come up before, > and so forgive me for beating a dead horse. Secondly, let me say that > Python's strength is its dynamic nature, and I don't believe that it > should ever require a precondition scaffolding. With that said, I do > believe that something like type hinting would be beneficial to the > Python community, both for tool enablement and for disambiguous > programming. > > [snip] > Thoughts? You may want to look at the various "adapt" ideas that have come along (prompted by Alex Martelli's http://www.python.org/peps/pep-0246.html). The two dominant implementations of this idea are PJE's PyProtocols, and Zope.Interfaces. I've used PyProtocols with great success in the past. The basic problem with type "hinting" is that it totally breaks duck typing, which is one of the reasons Python's dynamic nature is so powerful. Just because a function expects a "list object", I should not be prevented from passing in my own custom object that supports the necessary parts of the list protocol. This is where adaption makes its mark, as it is more about supported interfaces on an object than about actual types. It's also important to note that while Guido did spend a lot of time thinking about optional type markups (and this caused a LOT of hand wringing in the Python community, the general consensus in the end was that there was no real benefit from it. (I got the impression that a lot of the push was from Java/C++ people that didn't really understand what dynamic languages are about, and wanted to make Python more like Java/C++. Just my impression though). And in case you're thinking that maybe we could get some performance gains out of adding optional types, you should check out Brett Cannon's Master's thesis. In it, he actually added some typing markup to Python, and the end result was almost no gain. HOWEVER: If you feel this is something you still want to have a go at , PLEASE try it, and let the community know what your results were. It's making me sad that there's a lot of talk these days about how unwilling the Python community is to hear new ideas. And if you do decide to go forward with it, you should look at the 2.5 branch of the CPython code, as the new AST is supposed to make it *much* easier to experiment with changes to the language. Good luck! Jay P. From paul at boddie.org.uk Mon Mar 13 13:15:37 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 13 Mar 2006 10:15:37 -0800 Subject: Which GUI toolkit is THE best? References: <441172c2$1@news1.ethz.ch> Message-ID: <1142273736.875873.266880@e56g2000cwe.googlegroups.com> Thomas Guettler wrote: > > Have you read all the text? > > """ > Two qualities of the Qt Commercial License should be emphasized: > > You need it before you start development of proprietary software. > > You must purchase a Qt Commercial License from Trolltech or from any of > its authorized resellers before you start developing. The Commercial > license does not allow the incorporation of code developed with the Open > Source Edition of Qt into a proprietary product. > """ > > There is a GPL version for Linux. But the GPL does not allow linking > with closed source software. My understanding of how it all works is this: Trolltech offers you Qt under the GPL; you can choose to accept the GPL; you then uphold the GPL in the distribution of your work. Alternatively, you request that Trolltech license the software to you under the "Qt Commercial License"; they decide whether or not they want to license it to you; if they decide "yes", you get to distribute your proprietary software with the proprietary edition of the product. What people don't usually understand (or rather complain about loudly) is that Trolltech can refuse to license Qt to you under the commercial licence, as is their right as the owner of the copyrighted work. As far as I know, you can still obtain Qt under the GPL from them in such a situation, although this is fairly academic since there are lots of people offering Qt under the GPL in a variety of GNU/Linux distributions, for example. Usually, the people making a fuss about all this have already licensed Qt under the GPL, however, and believe that they have a right to "switch over" to another licence, but neither the GPL nor any basic aspect of copyright practice supports such a notion. So, yes, you either say up front that you're developing proprietary software and buy into that special deal with the copyright holder, or you don't. Of course, you could try and distribute non-commercial, evaluation, trial, educational-use-only, non-redistributable or NDA-affected versions of your favourite proprietary software products and see which court of law that takes you to - in these debates nobody seems to ask themselves whether Bill Gates and/or Steve Jobs would let you switch around, slip out of that NDA, give you special upgrades, strike through clauses in that EULA, and so on down the list of things that nobody thought about when putting together that now-shaky business model. Paul From reply.in.the.newsgroup at my.address.is.invalid Sat Mar 4 06:27:10 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 04 Mar 2006 12:27:10 +0100 Subject: How to except the unexpected? References: <4408db38$0$21898$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: Roy Smith: >I like to create a top-level exception class to encompass all the >possible errors in a given module, then subclass that. This way, if you >want to catch anything to goes wrong in a call, you can catch the top-level >exception class without having to enumerate them all. What do you propose to do with exceptions from modules called by the given module? -- Ren? Pijlman From grante at visi.com Thu Mar 2 16:24:20 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 02 Mar 2006 21:24:20 -0000 Subject: do design patterns still apply with Python? References: <8SINf.1718$No6.40137@news.tufts.edu> Message-ID: <120eok46fkf0j2b@corp.supernews.com> On 2006-03-02, John Salerno wrote: > Since Python does so many things different, especially compared to > compiled and statically typed languages, do most of the basic design > patterns still apply when writing Python code? Definitely. Especially plaid, paisley, and a nice medium houndstooth check. But please, not all at the same time. -- Grant Edwards grante Yow! Maybe we could paint at GOLDIE HAWN a rich PRUSSIAN visi.com BLUE -- From fredrik at pythonware.com Sat Mar 18 07:41:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 18 Mar 2006 13:41:19 +0100 Subject: how to deal with socket.error: (10060, 'Operation timed out') References: <1142685048.103592.129390@i39g2000cwa.googlegroups.com> Message-ID: "JuHui" wrote: > I wrote a script to get 100 pages from a server. > like below: > > 1:import httplib > 2:conns = httplib.HTTPConnection("www.mytest.com") > 3:conn.request("GET", "/") > sometimes a socket error was raised. > > File "D:\usr\bin\lib\httplib.py", line 627, in connect > raise socket.error, msg > socket.error: (10060, 'Operation timed out') (given the code you quoted, a NameError would be more likely...) > how to catch this kind of error then retry the "GET" operation? the same way as you'd catch any other kind of error in Python: try: except : if you want to repeat an operation until it succeeds, use a loop: while 1: try: except : else: break # success for details, see http://docs.python.org/tut/node10.html From scott.daniels at acm.org Thu Mar 23 15:07:24 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 23 Mar 2006 12:07:24 -0800 Subject: Function params with **? what do these mean? In-Reply-To: <1142887602.977736.300990@u72g2000cwu.googlegroups.com> References: <1142887602.977736.300990@u72g2000cwu.googlegroups.com> Message-ID: <4422fd92@nntp0.pdx.net> J Rice wrote: > I'm sorry for such a basic question, but I haven't been able to phrase > a search that gets me an answer and my books are totally silent on > this. I have seen a number of python function defs that take > parameters of the form (**param1). Looks like a pointer... but my > books on python (basic as they are) don't make a mention. What is > this? At the risk of being thought of as beating a dead horse, this was a _great_ way to ask this question. Others may note that nobody told you you were abusing the newsgroup to do your work for you; you told us how you tried to answer the question for yourself. So, anyhow, thanks for taking the time to write your question properly. -- -Scott David Daniels scott.daniels at acm.org From news at lolmc.com Mon Mar 20 13:49:02 2006 From: news at lolmc.com (bolly) Date: 20 Mar 2006 10:49:02 -0800 Subject: converting sqlite return values In-Reply-To: References: <1140465583.398495.63470@g44g2000cwa.googlegroups.com> Message-ID: <1142880542.495490.131770@i40g2000cwc.googlegroups.com> Hi Gerhard, Firstly my apologies for not replying sooner and secondly thanks for the advice.I went down the route of changing the data I was entering so that it was always an integer and zap - no more problems. Thanks again, Bolly From robert.kern at gmail.com Mon Mar 6 17:24:25 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 06 Mar 2006 16:24:25 -0600 Subject: Opening files without closing them In-Reply-To: <7xu0abgr12.fsf@ruckus.brouhaha.com> References: <1141598002.402189.275520@i40g2000cwc.googlegroups.com> <7xu0abgr12.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "3c273" writes: > >>>f = open(file) >>>try: >>> contents = f.read() >>>finally: >>> f.close() >>> >> >>Pardon the newbie question, but could you explain why? I have been doing it >>the same way as the OP and would like to know the difference. Thank you. > > Say that the open is inside the try block. If the file can't be > opened, then 'open' raises an exception, 'f' doesn't get set, and then > the 'finally' clause tries to close f. f might have been previously > bound to some other file (which still has other handles alive) and so > the wrong file gets closed. And even if 'f' wasn't bound to anything, you will get a NameError instead of the exception that you're really interested in seeing. -- Robert Kern robert.kern at gmail.com "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 Fri Mar 24 07:57:24 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 24 Mar 2006 04:57:24 -0800 Subject: Strange metaclass behaviour In-Reply-To: <1143203404.329141.194770@z34g2000cwc.googlegroups.com> References: <1143127358.820526.259930@i40g2000cwc.googlegroups.com> <1143138624.25186@news.aic.at> <1143188732.510491.233900@t31g2000cwb.googlegroups.com> <1143203404.329141.194770@z34g2000cwc.googlegroups.com> Message-ID: <1143205044.425097.32950@i39g2000cwa.googlegroups.com> Well, I would not call it a bug, I would call it to cheat ;) The assert is there I just wanted to prevent accidents, not to *really* ensure that 'thisclass' is called inside a class statement. Do you know of any reliable method to enforce that restriction? Michele Simionato From HiringDivision at gmail.com Sat Mar 25 14:11:17 2006 From: HiringDivision at gmail.com (HiringDivision at gmail.com) Date: 25 Mar 2006 11:11:17 -0800 Subject: HIRING: PHP Developer Message-ID: <1143313877.802242.206050@i40g2000cwc.googlegroups.com> From: In Need - view profile Date: Fri, Mar 24 2006 10:39 pm Email: "In Need" Groups: hfx.forsale Not yet ratedRating: show options Reply | Reply to Author | Forward | Print | Individual Message | Show original | Report Abuse | Find messages by this author We are hiring a PHP developer! The site must contain the following: - database - administrator panel (implementing multiple employee logins / permissions) - credit card / paypal processing - affiliate program - news scripting control panel - image design - coupons / discounts, & gift certificates - customer log in / log out - specials page - contests - forum Would like to have: - flash design - various language support - pages that have pre-loaded data (click the link and no new page opens within the main frame. Simply brings the information forward). The individual(s) that are selected for this project will have the opportunity to remain our company's web and image designer(s). Please send a price quote for the above mentioned request, as well as a quote for a design similar to www.IGE.com to HiringDivision at gmail.com. Thank you. From rrr at ronadam.com Sun Mar 12 21:15:19 2006 From: rrr at ronadam.com (Ron Adam) Date: Sun, 12 Mar 2006 20:15:19 -0600 Subject: Cheese Shop: some history for the new-comers In-Reply-To: <1142195692.744899.129390@j52g2000cwj.googlegroups.com> References: <44126523$0$1016$afc38c87@news.optusnet.com.au> <1142195692.744899.129390@j52g2000cwj.googlegroups.com> Message-ID: jjcassidy at gmail.com wrote: > richard wrote: > [snip] > Should the "Python Cheeseshop" have anything in it, though? Having a > stocked cheese shop in relation to Python is just silly! Cheese (or the lack of cheese) is never silly, Thus the slogan... "The power of cheese". Now if you want silliness, then the correct establishment for that is "The Ministry of Silly Walks". ;) Ron From enleverlesX.XmcX at XmclaveauX.com Mon Mar 20 14:52:13 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Mon, 20 Mar 2006 20:52:13 +0100 Subject: Win32 ActiveX with COM support References: <1142866971.191129.313460@g10g2000cwb.googlegroups.com> Message-ID: <441f0ef5$0$20145$8fcfb975@news.wanadoo.fr> Hi! >>>Can I create a COM server / client component set with Python? Yes. Michel Claveau From no-spam at no-spam-no-spam.com Fri Mar 17 04:55:00 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Fri, 17 Mar 2006 10:55:00 +0100 Subject: Pythonic debugging - Re: Python Debugger / IDE ?? In-Reply-To: <4417236d$0$7100$626a54ce@news.free.fr> References: <1142357338.313046.139060@i39g2000cwa.googlegroups.com> <4417236d$0$7100$626a54ce@news.free.fr> Message-ID: bruno at modulix wrote: > krypto.wizard at gmail.com wrote: > >>Is there any editor or IDE in Python (either Windows or Linux) which >>has very good debugging facilites like MS VisualStudio has or something >>like that. >> >>I like SPE but couldn't easily use winPDP. I need tips to debug my code >>easily. > > > pythonic "debugging" in three steps: > > 1/ unit tests > 2/ a bunch of print statements > 3/ the interactive python shell > > All this relying on well-decoupled, modular code. > > FWIW, I've almost never used a debugger with Python. Thats a good socket for Python. Arduos step-in debugging, big tedious remote debugging sessions etc. are not really Pythonic. For complex things like GUI's and application servers its a weak practice. logs, postmortem debugging and ad-hoc debugging are the things to go next. so its good when you can do .pm() .set_trace() to call the debugger from the nature of your program. (And not: "The the debugger now calls the app, once my level of anger raised beyond a certain limit"). For example with callable debuggers like pdb and also Pythonwin (Pythonwin debugger "pywin.debugger.pm()" e.g. can be raised as simple from normal apps / shell ) I simply do this in apps regularly: if debug: sys.excepthook = excepthook_my_debugger As soon as stuff crashes down (even in GUI message handlers) during all of the development cycle: you have your fingers and cursor automatically & immediatly at the stack context. That does >99% of usual python code cooking. The rest is maybe for a (slow) breakpoint "b" Unfortunately such method is not encouraged and exposed (clearly) in the big IDE's. Those' overall style is a lazy copy of C, Java "I do"-hacker history. Im curious much about their value at all. Keep it simple and let Python do. Robert From bdesth.quelquechose at free.quelquepart.fr Sun Mar 19 18:26:13 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 20 Mar 2006 00:26:13 +0100 Subject: Counting number of each item in a list. In-Reply-To: <1142796177.711806.41150@g10g2000cwb.googlegroups.com> References: <1142772092.958602.272260@e56g2000cwe.googlegroups.com> <441d58f7$0$13046$626a54ce@news.free.fr> <1142774630.426660.19970@t31g2000cwb.googlegroups.com> <441d6342$1_3@newspeer2.tds.net> <441d9408$0$20430$636a55ce@news.free.fr> <441dab21$0$27059$626a54ce@news.free.fr> <1142796177.711806.41150@g10g2000cwb.googlegroups.com> Message-ID: <441DE895.1080609@free.quelquepart.fr> Justin Azoff a ?crit : > Bruno Desthuilliers wrote: > >>And of course, I was right. My solution seems to be faster than Paul's >>one (but slower than bearophile's), be it on small, medium or large lists. > > > Your version is only fast on lists with a very small number of unique > elements. > > changing mklist to have > items = range(64) instead of the 9 item list and re-timing you will get > "better" results: > > A100 (10000 times): 7.63829684258 > B100 (10000 times): 1.34028482437 > C100 (10000 times): 0.812223911285 > > A10000 (100 times): 9.78499102592 > B10000 (100 times): 1.26520299911 > C10000 (100 times): 0.857560873032 > > A1000000 (10 times): 87.6713900566 > B1000000 (10 times): 12.7302949429 > C1000000 (10 times): 8.35931396484 > Lol !-) So much for my benchmarking skills... From fuzzyman at gmail.com Mon Mar 27 07:22:01 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 27 Mar 2006 04:22:01 -0800 Subject: Difference between 'is' and '==' In-Reply-To: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> Message-ID: <1143462121.828462.34290@v46g2000cwv.googlegroups.com> mwql wrote: > Hey guys, this maybe a stupid question, but I can't seem to find the > result anywhere online. When is the right time to use 'is' and when > should we use '=='? > > Thanks alot~ '==' is the equality operator. It is used to test if two objects are 'equal'. 'is' is the identity operator, it is used to test if two names/references point to the same object. a = {'a': 3} b = {'a': 3} a == b True a is b False c = a a is c True The two dictionaries a and b are equal, but are separate objects. (Under the hood, Python uses 'id' to determine identity). When you bind another name 'c' to point to dictionary a, they *are* the same object - so a *is* c. One place the 'is' operator is commonly used is when testing for None. You only ever have one instance of 'None', so a is None is quicker than a == None (It only needs to check identity not value.) I hope that helps. Fuzzyman http://www.voidspace.org.uk/python/index.shtml From godoy at ieee.org Fri Mar 24 11:55:38 2006 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 24 Mar 2006 13:55:38 -0300 Subject: What's The Best Editor for python References: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> Message-ID: <87mzffye7p.fsf@ieee.org> "PythonStudent" writes: > Can one of you say to me what's the best editor for editing the python > programs ( for linux or windows ), and if you can send it to me to the > adresse Ahcheriet at gmail.com Emacs runs on both. So do Eclipe and a lot of other... What is best? The one that solves your problems without getting in your way. -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From uche.ogbuji at gmail.com Fri Mar 17 17:01:42 2006 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 17 Mar 2006 14:01:42 -0800 Subject: How to search XML? Are there special libs? In-Reply-To: <1142591921.145818.93720@z34g2000cwc.googlegroups.com> References: <1142563251.715961.304060@j33g2000cwa.googlegroups.com> <47vg4uFgspbpU1@uni-berlin.de> <1142591921.145818.93720@z34g2000cwc.googlegroups.com> Message-ID: <1142632902.935337.320390@i40g2000cwc.googlegroups.com> Ravi Teja wrote: > Yes! XPath is a good bet. > You can also try some Pythonic XML libraries like Amara. You need not > learn any special language even. > > There are good database approaches to XML too, especially if you are > going to query a document collection as a whole rather than file by > file. You can try XQuery. I think 4Suite can do this (But I am too > sleepy to confirm :-) ). You also use eXist (Java but you can use > XMLRPC or SOAP to interface with it from Python). Not optimal like > parent said, but if it is XML that have to live with ... 4Suite does not support XQuery. It does support full XPath plus EXSLT and enough other extensions to come close to the power of XQuery. Amara [1] makes it really easy to get XQuery-like power from right within Python, as I've blogged before (e.g. [2][3]). I don't know whether full-text indexing of XML is something the OP needs as well. If so, see [3]. [1] http://uche.ogbuji.net/tech/4Suite/amara/ [2] http://copia.ogbuji.net/blog/2005-06-12/Amara_equi [3] http://copia.ogbuji.net/blog/2005/Sep/20 [4] http://www.xml.com/pub/a/2004/12/08/py-xml.html -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ From scott.daniels at acm.org Fri Mar 3 12:31:41 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 03 Mar 2006 09:31:41 -0800 Subject: in need of some sorting help In-Reply-To: <1141360027.951400.173750@j33g2000cwa.googlegroups.com> References: <1141275649.856712.313540@p10g2000cwp.googlegroups.com> <1141360027.951400.173750@j33g2000cwa.googlegroups.com> Message-ID: <44087ba3$1@nntp0.pdx.net> ianar? wrote: > .... > files.sort(key=lambda x: x.lower()) > files.sort(key=lambda x: os.path.dirname(x)) This is exactly why some of us hate lambda. It encourages long-way-around thinking. files.sort(key=lambda x: os.path.dirname(x)) is better written as: files.sort(key=os.path.dirname) Learn to have your skin itch when you see: ... lambda name:(name) And yes, I concede that it _is_ useful in your .lower expression. It's not that lambda is bad, rather that it seems to encourages this 'lambda x:f(x)' stuff. --Scott David Daniels scott.daniels at acm.org From jjl at pobox.com Thu Mar 23 17:40:06 2006 From: jjl at pobox.com (John J. Lee) Date: 23 Mar 2006 22:40:06 +0000 Subject: Can't get the real contents form page in internet as the tag "no-chche" References: <1143080278.976802.233340@u72g2000cwu.googlegroups.com> <48fcu2Fjrf0dU1@uni-berlin.de> <1143112651.093751.128800@u72g2000cwu.googlegroups.com> Message-ID: <878xr0g4zd.fsf@pobox.com> "dongdong" writes: > oh~~~! offer my thanks to Tim Roberts and all persons above! > I see now, it's the different url causes! > contents can only be got from the later (real ) url. > I made a mistick not to look at the different urls taking effect. If you use ClientCookie.urlopen() in place of urllib2.urlopen(), it will handle Refreshes and HTTP-EQUIV for you transparently. Actually, you have to explicitly ask for that functionality: import ClientCookie opener = ClientCookie.build_opener(ClientCookie.HTTPEquivProcessor, ClientCookie.HTTPRefreshProcessor, ) ClientCookie.install_opener(opener) print ClientCookie.urlopen(url).read() If you want to do even less of this stuff "by hand", class Browser from module mechanize is a subclass of the class of "opener" above, but behaves much more like a web browser in various ways. Still alpha, but very near now to stable release. FWIW, you can also use ClientCookie.HTTPRefreshProcessor, ClientCookie.HTTPEquivProcessor etc. with Python 2.4's urllib2, as long as you follow the instructions under the heading "Notes about ClientCookie, urllib2 and cookielib" in the ClientCookie README file (specifically, if you want to use ClientCookie.RefreshProcessor with Python 2.4's urllib2, you must also use ClientCookie.HTTPRedirectHandler). John From robert.kern at gmail.com Tue Mar 14 20:12:58 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 14 Mar 2006 19:12:58 -0600 Subject: markov query In-Reply-To: <1142378132.911751.324180@i40g2000cwc.googlegroups.com> References: <1142309974.440477.192600@u72g2000cwu.googlegroups.com> <1142378132.911751.324180@i40g2000cwc.googlegroups.com> Message-ID: kpp9c wrote: >>Yes, a system which does this has to build a Markov >>chain from a data set and then traverse it. > >>>Any program that actually uses Markov chains to generate >>>new text based on existing input as you've described > > Hi. That isn't really what i have described. If i did i could use > exsisting algorithms. What you describe is exactly what i don't want in > this particular case. I am actually not wanting it to build a chain > from some input that it analyzes. There is no input. If you see, i am > trying to define a table that tells it how to proceed forward from > scratch as a stochastic process. Any such program has two main parts, one that trains the transition matrix from a data set, and one that generates output from that transition matrix. You should be able to take such a program and only use the latter component with your transition matrix, however you choose to create it. Googling for 'python markov' generates several leads. -- Robert Kern robert.kern at gmail.com "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 meeper34 at gmail.com Wed Mar 15 10:33:57 2006 From: meeper34 at gmail.com (meeper34) Date: 15 Mar 2006 07:33:57 -0800 Subject: newbie questions Message-ID: <1142436837.547047.308520@j52g2000cwj.googlegroups.com> Hi, I'm just starting out with Python, and so far I am thoroughly impressed with what you can do very easily with the language. I'm coming from a C++ background here. A couple of questions came up as I was thinking about dynamically typed languages: 1. If someone releases an interface in Python, how does the user know what parameters the function takes/returns? 2. If documentation is the answer to 1, then are there any Python documentation standards? 3. Are there any tools out there that can extract the interface information from Python files and release it as documentation like header (.h) files? I know there are tools like this for languages like C#. 4. Really basic question, and I'm sure I will learn this very quickly with more reading, but I'm confused by the lack of an entry point in a Python app, i.e. int main(). Btw, I was turned on to Python from Bruce Eckel's article "Strong Typing vs Strong Testing." Thanks, John From johnjsal at NOSPAMgmail.com Sat Mar 25 02:00:47 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 25 Mar 2006 02:00:47 -0500 Subject: a problem to solve In-Reply-To: <1143269510.239870.79570@e56g2000cwe.googlegroups.com> References: <5oiUf.1818$No6.41433@news.tufts.edu> <1143237220.103038.52200@t31g2000cwb.googlegroups.com> <1143251777.489064.28690@u72g2000cwu.googlegroups.com> <66idnRFWy481ebnZnZ2dnUVZ_vydnZ2d@rcn.net> <1143269510.239870.79570@e56g2000cwe.googlegroups.com> Message-ID: mensanator at aol.com wrote: > John Salerno wrote: >> John Salerno wrote: >>> mensanator at aol.com wrote: >>> >>>> No. First of all, combining them with the & operator would be >>>> the asnswer to having all four lamps lit in the same position. >>>> But you want exactly 3 (in any combination). The correct way >>>> to combine the switches (using my answer of a[7] b[2] c[5] d[3]) >>>> is to use the boolean expression I gave you initially: >>> Ah, that makes sense. I think I have a handle on it now. Of course, you >>> did the grunt work of making the hex list, which might not have been so >>> fun, but now I can work on using it to get the solution. Once I do, I'd >>> love to compare my answer to yours, because something tells me yours >>> will be much more elegant. :) >> p.s. is there an xor operator in python? > > Yep. The XOR operator is ^. That's why you have to use ** > for exponentiation. In addition to &=AND, there is also > |=OR. I actually gave two boolean expressions. > > First, using the standard notation, where concatenation implies > AND, + is OR and x is XOR (actually, the standard notation > for XOR is a + inside a circle, but my keyboard doesn't have > one of those). > > Y = CD(A x B) + AB(C x D) > > Second, using the Python operators > > Y = ((C & D) & (A ^ B)) | ((A & B) & (C ^ D)) > Thanks! Back to work for me! :) From mnations at gmail.com Sat Mar 18 23:20:22 2006 From: mnations at gmail.com (Mudcat) Date: 18 Mar 2006 20:20:22 -0800 Subject: Need design advice. What's my best approach for storing this data? In-Reply-To: References: <1142615283.733346.74260@i40g2000cwc.googlegroups.com> Message-ID: <1142742022.415092.243210@g10g2000cwb.googlegroups.com> In doing a little research I ran across PyTables, which according to the documentation does this: "PyTables is a hierarchical database package designed to efficiently manage very large amounts of data." It also deals with compression and various other handy things. Zope also seems to be designed to handle large amounts of data with compression in mind. Does any know which of these two apps would better fit my purpose? I don't know if either of these has limitations that might not work out well for what I'm trying to do. I really need to try and compress the data as much as possible without making the access times really slow. Thanks From fabiofz at gmail.com Fri Mar 31 11:26:22 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Fri, 31 Mar 2006 13:26:22 -0300 Subject: Best IDE for Python? In-Reply-To: References: <1143783179.361616.76750@i39g2000cwa.googlegroups.com> <1143813623.203852.184000@g10g2000cwb.googlegroups.com> <1143816395.190171.298530@t31g2000cwb.googlegroups.com> <1143819878.126552.46160@g10g2000cwb.googlegroups.com> Message-ID: On 3/31/06, Keith B. Perry wrote: > > You are probably right, and I will definitely take a look at the starter > manual. Hopefully it also works well on classes that I create? You got > some nice docs there. > Surely does ;-) Cheers, Fabio Thanks for the tip! > > > On 3/31/06, Fabio Zadrozny wrote: > > > Well, in pydev you surely can have code-completion on 'math.' > > > > I think you got some wrong configuration... Have you read the getting > > started manual? ( http://www.fabioz.com/pydev/manual_101_root.html) > > > > > > On 31 Mar 2006 07:44:38 -0800, kbperry < keith.b.perry at gmail.com> > > wrote: > > > > > To me, it just doesn't behave the same way as Eclipse for java. I > > have > > used the plug-in, and I usually use it on my home machine ( I am still > > a student). For example, in Java eclipse, if you import a module like > > math, then if you want to use a math function, you just type math + > > period, and then all the functions pop up in a scroll menu. I love > > this. I am not searching through online documentation...etc just to > > find some stupid method/function that I know is there. It doesn't seem > > to behave like this for Python....I wish it did. > > > > I still love programming in Python, though. > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dprovins at rpcl.com Thu Mar 30 10:46:58 2006 From: dprovins at rpcl.com (Dean Allen Provins) Date: Thu, 30 Mar 2006 15:46:58 GMT Subject: printing under MS win Message-ID: <442BFDB6.7060607@rpcl.com> Hi: My Linux-based Python/Tkinter application runs nicely, and printing works just fine (to a user-selected file, or an "lpr" device specified in the Entry box). Alas, the user wants to run it under MS Win, and of course will want to print the canvas for posterity. A Google search turned up a similar request from many years ago, which seemed to go unanswered. My current thoughts are 1) get the user to print to a file and let him copy the file to his printer (which is postscript); 2) do much the same as (1), but let the user display and print under Ghostscript/Ghostview; and 3) get the user to install UNIX printing services (which I found not to be trivial when I had to do it once) and then printing will run much as it does on UNIX/Linux. Any thoughts or other ideas? Regards, Dean Calgary From robert.kern at gmail.com Sat Mar 4 18:11:47 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 04 Mar 2006 17:11:47 -0600 Subject: Advice from distutils experts? In-Reply-To: <1141510795.163142.300480@t39g2000cwt.googlegroups.com> References: <1141510795.163142.300480@t39g2000cwt.googlegroups.com> Message-ID: olsongt at verizon.net wrote: > I'm doing something a little wierd in one of my projects. I'm > generating a C source file based on information extracted from python's > header files. Although I can just generate the file and check the > result into source control, I'd rather have the file generated during > the install process instead of doing it manually. > > So I'd like to: > + have the file generated when a unix user runs setup.py install. > + have the file generated when I create a windows binary > distribution. > + not have the file generated when I create source distribution > .tgz's and .zip's. > > I'd appreciate any pointers on the best way to hook into disutils to do > this. And if the answer is "Your crazy, generate the file outside of > distutils." just let me know. We do things like this in numpy. We've extended distutils to allow functions in the sources list for Extension. from numpy.distutils.core import Extension from distutils.dep_util import newer def generate_source_c(ext, build_dir): target = os.path.join(build_dir, 'source.c') if newer(__file__, target): # ... parse Python headers contents = """ #include "Python.h" /* ... */ """ % (stuff, more_stuff) f = open(target, 'w') f.write(contents) f.close() return target ext = Extension('my_extension', sources=[generate_source_c], ) setup(#... ext_modules=[ext] ) -- Robert Kern robert.kern at gmail.com "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From jstroud at ucla.edu Wed Mar 8 23:56:43 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 08 Mar 2006 20:56:43 -0800 Subject: advice on this little script In-Reply-To: References: <2bSdncqWK7aJN5LZRVn-vA@rcn.net> <120vb889343kd1@corp.supernews.com> Message-ID: John Salerno wrote: > Grant Edwards wrote: > >> On 2006-03-09, John Salerno wrote: >> >>> from time import sleep >>> >>> minutes = input('Enter the number of minutes to wait: ') >>> >>> for x in range(minutes): >>> sleep(1.0) >>> minutes -= 1 >>> print minutes, 'minutes remaining.' >> >> >> for x in range(minutes,0,-1): >> sleep(60.0) >> print minutes, 'minutes remaining' >> > > I might be doing something wrong, but this just keeps printing out '10 > minutes remaining' each time. print x, 'minutes remaining' -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From steven.bethard at gmail.com Wed Mar 1 19:55:00 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 01 Mar 2006 17:55:00 -0700 Subject: Proper class initialization In-Reply-To: <44063c9f$0$25069$4d3efbfe@news.sover.net> References: <44063c9f$0$25069$4d3efbfe@news.sover.net> Message-ID: Leif K-Brooks wrote: > Steven Bethard wrote: >> class A(object): >> def _get_sum(): >> return sum(xrange(10)) >> sum = _get_sum() > > What's wrong with sum = sum(xrange(10))? Nothing, except that it probably doesn't answer the OP's question. The OP presented a "silly example": class A: sum = 0 for i in range(10): sum += i I assume the intention was to indicate that the initialization required multiple statements. I just couldn't bring myself to write that horrible for-loop when the sum() function is builtin. ;) STeVe From keir.robinson at gmail.com Wed Mar 15 11:03:43 2006 From: keir.robinson at gmail.com (keirr) Date: 15 Mar 2006 08:03:43 -0800 Subject: newbie questions References: <1142436837.547047.308520@j52g2000cwj.googlegroups.com> Message-ID: <1142438622.964221.17350@z34g2000cwc.googlegroups.com> meeper34 wrote: > Hi, > > I'm just starting out with Python, and so far I am thoroughly impressed > with what you can do very easily with the language. I'm coming from a > C++ background here. A couple of questions came up as I was thinking > about dynamically typed languages: > > 1. If someone releases an interface in Python, how does the user know > what parameters the function takes/returns? > > 2. If documentation is the answer to 1, then are there any Python > documentation standards? > > 3. Are there any tools out there that can extract the interface > information from Python files and release it as documentation like > header (.h) files? I know there are tools like this for languages like > C#. > epydoc: http://epydoc.sourceforge.net/ is used by a bunch of people - including me. The documentation it produces is far from a header file, typically it is in HTML (although other output formats are available) but I find it does. > 4. Really basic question, and I'm sure I will learn this very quickly > with more reading, but I'm confused by the lack of an entry point in a > Python app, i.e. int main(). There is some idiom for this. def main(*args, **kw): # do stuff pass if __name__ == '__main__': # call main, perhaps with sys.argv main() You put this at the bottom of the file you want to run. The __name__ property will be '__main__' iff you have executed the file from the command line. In particular the code in the if __name__... block won't be run if you just import the file. All the best, Keir. > Btw, I was turned on to Python from Bruce Eckel's article "Strong > Typing vs Strong Testing." > > Thanks, > John From rice.jeffrey at gmail.com Mon Mar 20 15:46:43 2006 From: rice.jeffrey at gmail.com (J Rice) Date: 20 Mar 2006 12:46:43 -0800 Subject: Function params with **? what do these mean? Message-ID: <1142887602.977736.300990@u72g2000cwu.googlegroups.com> I'm sorry for such a basic question, but I haven't been able to phrase a search that gets me an answer and my books are totally silent on this. I have seen a number of python function defs that take parameters of the form (**param1). Looks like a pointer... but my books on python (basic as they are) don't make a mention. What is this? Jeff From moretti at igs.cnrs-mrs.fr Mon Mar 13 02:43:34 2006 From: moretti at igs.cnrs-mrs.fr (Moretti) Date: Mon, 13 Mar 2006 08:43:34 +0100 Subject: [How to change redirect stderr?] References: Message-ID: Fredrik Lundh wrote: > "Moretti" wrote: > >> I would like to be able to change the standard error path. > > (I'm not sure path is the right word here, really, but never mind...) > >> How can I do this in a script if I want to send error messages to >> /dev/null by example ? > > if you're talking about things that Python prints to stderr, all you need > to do is to replace sys.stderr with something more suitable: > > import sys > sys.stderr = open("/dev/null", "w") > > or, more portable: > > class NullDevice: > def write(self, s): > pass > > sys.stderr = NullDevice() > > if you want to redirect both things printed via sys.stderr and things > printed to stderr at the C level, you need to redirect the STDERR file > handle. here's one way to do that: > > import os, sys > > sys.stderr.flush() > err = open('/dev/null', 'a+', 0) > os.dup2(err.fileno(), sys.stderr.fileno()) > > hope this helps! > > Thanks It's exactly what I seek for. -- Sebastien Moretti From gongcheng_g at hotmail.com Fri Mar 24 04:55:35 2006 From: gongcheng_g at hotmail.com (ChengGong) Date: 24 Mar 2006 01:55:35 -0800 Subject: About Image Size In-Reply-To: <1143191797.808812.265730@i39g2000cwa.googlegroups.com> References: <1143191797.808812.265730@i39g2000cwa.googlegroups.com> Message-ID: <1143194135.231669.89830@v46g2000cwv.googlegroups.com> Problem was solved thanks Cheng From doug at localhost.localdomain Thu Mar 16 15:18:19 2006 From: doug at localhost.localdomain (Doug) Date: Thu, 16 Mar 2006 20:18:19 GMT Subject: Python / glade fundamentals Message-ID: Hi all, Can someone tell me why I do not get a connection between the events and the functions in the sample below. GUI window appears OK, just no connections seem to be made. I am new to this so may be missing something fundamental. Thanks, Doug file pgtest.glade ================= True GDK_KEY_PRESS_MASK PGtestWindow GTK_WINDOW_TOPLEVEL GTK_WIN_POS_NONE False 640 480 True True True False False GDK_WINDOW_TYPE_HINT_NORMAL GDK_GRAVITY_NORTH_WEST True GDK_KEY_PRESS_MASK GDK_EXTENSION_EVENTS_ALL file pgtest.py ============== import gtk import gtk.glade def on_drawingarea1_key_press(widget): print "keypress" xml = gtk.glade.XML('pgtest.glade') widget = xml.get_widget('drawingarea1') #print type(xml) xml.signal_autoconnect({ "on_drawingarea1_key_press_event": on_drawingarea1_key_press, "on_page_destroy_event":gtk.mainquit }) gtk.main() From ptmcg at austin.rr.com Thu Mar 30 19:18:51 2006 From: ptmcg at austin.rr.com (Paul McGuire) Date: 30 Mar 2006 16:18:51 -0800 Subject: Identifying filled circles in a scanned image In-Reply-To: References: <1143762138.228681.228570@i40g2000cwc.googlegroups.com> Message-ID: <1143764331.446070.200460@v46g2000cwv.googlegroups.com> Douglas Douglas wrote: > The problem is that when the scanner takes the pages it > doesn't put it in the same exact position in its bed. There's not a lot of > difference, but there's a little. Your forms should have some reference registration marks or targets in opposite corners. Find these first, then you should be able to interpolate pixel positions from there, using a 2D trans/rotational transform. -- Paul From cfbolz at gmx.de Mon Mar 27 09:10:30 2006 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Mon, 27 Mar 2006 16:10:30 +0200 Subject: Next PyPy Sprint: Tokyo 23/4 - 29/4 Message-ID: Tokyo PyPy Sprint: 23rd - 29th April 2006 ============================================================ The next PyPy sprint is scheduled to take place 23rd- 29th April 2006 (Sunday-Saturday) in Akihabara, Tokyo, Japan. We will together with FSIJ (Free Software Initiative of Japan) aim to promote Python and PyPy. We therefor invite Japanese hackers knowledgeable in Python to join our sprint! We'll give newcomer-friendly introductions. To learn more about the new Python-in-Python implementation look here: http://codespeak.net/pypy For this sprint we are particularly interested in meeting and coding on PyPy together with interested Japanese Python hackers. Please register your interest at pypy-sprint at codespeak.net as soon as possible and we will help with any questions regarding getting started, pointing to relevant documentation etc. The PyPy team is curious and interested in the experience of hacking code for embedded devices and would love to discuss and get feedback on optimisation efforts and the current state of PyPy. Goals and topics of the sprint ------------------------------ Possible suggestions for topics are: - Work on gensqueak (our Squeak backend) or possibly other backends. - Implementing Python 2.5 features in PyPy. - Progress further on an 'rctypes' module aiming at letting us use a ctypes implementation of an extension module from the compiled pypy-c. - Writing ctypes implementations of modules to be used by the above tool. - Experimenting and improving performance of our garbage collectors. - Experiment with PyPy flexibility or other aspects of the implementation. - Possibly experiment with writing modules translatable for use both in PyPy and CPython. - Whatever participants want to do with PyPy or particular areas of PyPy (please send suggestions to the mailing list before to allow us to plan and give feedback) Location & Accomodation ------------------------ The sprint will be held at National Institute of AIST (National Institute of Advanced Industrial Science and Technology, http://www.aist.go.jp/index_en.html), Akihahabara (the technical gadget district in Tokyo). Yutaka Niibe is our contact person there, helping with arranging facilities. Niibe is the chairman of FSIJ and they have invited us to sprint in Tokyo and we are very grateful for the help and interest we have recieved so far. The facilities we are sprinting in are located here: http://www.gtrc.aist.go.jp/en/access/index.html#Akihabara The actual address is: Akihabara Dai Bldg , 1-18-13 Sotokanda, Chiyoda-ku, Tokyo 101-0021 Japan Phone: +81-3-5298-4729 Hotel areas - we are recommended to book hotels in Ueno and Asakusa (old town), from those areas there are only two metro stops to Akihabara. Please note that hotelrooms in Tokyo are often very small. http://www.wh-rsv.com/english/akihabara/index.html (nearest hotel to sprint location) http://www.greenhotel.co.jp/ochanomizu_e.html http://www.ohgai.co.jp/index-e.html (Ueno) http://www.toyoko-inn.com/e_hotel/00012/index.html (Asakusa) http://www.hotelnewkanda.com/ (second nearest, but no english page) Here is a url for booking hotels with not too unreasonable rates (see map): http://japan-hotelguide.com/hotels/Japan/Tokyo/index.htm For more general tourist information about travelling to Japan and Tokyo - please see: http://www.jnto.go.jp/eng/ http://www.japantravelinfo.com/ (really useful information regarding airfares, hotels, currency, phones etc etc) Comments on the weather: In end April it is ca 20 degrees Celsius. Exact times ----------- The public PyPy sprint is held Sunday 23rd - Saturday 29th April 2006. Hours will be from 10:00 until people have had enough. It's a good idea to arrive a day before the sprint starts and leave a day later. Sometimes people cannot stay for the whole sprint - you are welcome even if you can only stay for a day or a few days. Sunday: Starting at 10:00. This day is focused on getting to know PyPy enought to start to participate. We will hold a PyPy tutorial and an architectural overview. Planning meeting for the work to be done during the week and grouping of developers (pairs or groups mixing new participants with core developers). Dinner in the evening (Yutaka will arrange a place for us to go to). Monday-Tuesday: Starting at 10:00 with status meetings. Possible regrouping depending on the interest and progress of the various teams. Wednesday: Breakday (coding is allowed although we recommend taking a break). Thursday-Saturday: Starting at 10:00 with status meetings. Possible regrouping depending on the interest and progress of the various teams. Ending on Saturday with a Closure session - summing of the work and planning work to be done until the next sprint. Network, Food, currency ------------------------ We will have access to WiFi at AIST - please make sure you have wlan capabilities. Electricity outlets: 100V (adapters needed for european standard). Currency is Japanese yen. There are Citibank cash machines that accepts cash withdrawals from the major cards such as VISA and Mastercard. But it is a good idea to bring cash. Also note that cell phones (european) are not very compatible with the Japanese network. There are possibilities for 3G phones to hire a phone and put your simcard in there. At the airport (both Kansai and Narita) there are information and places were this can be arranged (to a cost of course). Food: well - japanese food is great (wether it is sushi, sashimi, tempura, sukiyaki, teriyaki.... Eating out is not that much differently prized than any large european town. There are of course restaurants serving other food than japanese (chinese, korean, McDonalds ;-). Please also note that vegetables and fruit is quite expensive in Japan. For more information - see tourist url:s above. Registration etc.pp. -------------------- Please subscribe to the `PyPy sprint mailing list`_, introduce yourself and post a note that you want to come. Feel free to ask any questions there! There also is a separate `Tokyo people`_ page tracking who is already thought to come. If you have commit rights on codespeak then you can modify yourself a checkout of http://codespeak.net/svn/pypy/extradoc/sprintinfo/tokyo/people.txt .. _`PyPy sprint mailing list`: http://codespeak.net/mailman/listinfo/pypy-sprint .. _`Tokyo people`: http://codespeak.net/pypy/extradoc/sprintinfo/tokyo/people.html _______________________________________________ pypy-dev at codespeak.net http://codespeak.net/mailman/listinfo/pypy-dev _______________________________________________ Python-Dev mailing list Python-Dev at python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/python-python-dev%40m.gmane.org From rjagodic at gmail.com Mon Mar 6 20:22:58 2006 From: rjagodic at gmail.com (Ratko Jagodic) Date: Mon, 6 Mar 2006 19:22:58 -0600 Subject: figuring out how much data was sent so far via XML-RPC? Message-ID: <1eb708be0603061722y7f751902ha1216f7636f16425@mail.gmail.com> I am currently using XML-RPC for a very convenient quick-and-dirty way of sending some files (base64 encoded). The files can be bigger sometimes (10-20mb) and I was wondering if there is a way to see how much data was sent already and how much still needs to be sent (like a progress bar). I would of course need that only on the client side. I know how I would do it with pure sockets but I am not sure how could I get to that lower level with xmlrpclib... I am using xmlrpclib.ServerProxy for the client and a SimpleXMLRPCServer. It would also be great if I could keep the solution (if it exists) within the standard python library (no extra modules) because I am distributing this to other people. Thanks in advance! Ratko -------------- next part -------------- An HTML attachment was scrubbed... URL: From rtw at freenet.co.uk Sun Mar 26 06:36:19 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sun, 26 Mar 2006 05:36:19 -0600 Subject: SSH, remote login, and command output References: Message-ID: Spire 01 wrote in news:mailman.3688.1143360926.27775.python-list at python.org in comp.lang.python: > Greetings! > > I'm working on a Python program for a small LAN of Linux systems > running Gentoo, and I need a little help figuring out what I need to > do it. So what I'd like to do is, from any given computer, log on to > every other computer, run a certain command (which normally outputs > text to the terminal), and store the output so I can use the aggregate > statistics later in the program. > I would normally something along the lines of SSH to do it, but I > don't > know what I would need to pull that off in Python. There's also one > complication: the systems could be Gentoo systems, or they could be > logged into Windows since they're dual booted. Considering all of > this, can anyone give me some recommendation as to what library I > should learn how to use to pull this off? I admit, I haven't done too > much in the way of networks, but if someone can tell me what I need to > do remote logins in this way, I'll do what I can to make it work. > I found this: http://pyssh.sourceforge.net/ which may be able to help you script ssh, alternativly use the subprocess module: http://docs.python.org/dev/lib/module-subprocess.html and translate however you would "normaly" script ssh. To connect to windows, you could install: http://sshwindows.sourceforge.net/ on your windows clients, but IIRC its win2K, XP only, or you could use cygwin (which the above is taken from). Rob. -- http://www.victim-prime.dsl.pipex.com/ From exarkun at divmod.com Mon Mar 27 11:21:28 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 27 Mar 2006 11:21:28 -0500 Subject: encode short string as filename (unix/windows) In-Reply-To: <48qhbmFl85cbU1@uni-berlin.de> Message-ID: <20060327162128.22481.2088205713.divmod.quotient.6195@ohm> On Mon, 27 Mar 2006 18:13:17 +0200, "Diez B. Roggisch" wrote: >robert wrote: > >> want to encode/decode an arbitrary short 8-bit string as save filename. >> is there a good already builtin encoding to do this (without too much >> inflation) ? or re.sub expression? > >Yuu could use the base64-encoder. Disadvantage is clearly that you can't >easily read your original text. Alternatively, three is that encoding that >is used by e.g. emails if you have an umlaut in a name. I _think_ it is >called puny-code, but I'm not sure how and if you can use that from within >python - google yourself :) punycode is used by dns. A commonly used email codec is quoted-printable. Here's an example of each: >>> u'Hell? world'.encode('utf-8').encode('quopri') 'Hell=C3=B3=20world' >>> u'Hell? world'.encode('punycode') 'Hell world-jbb' >>> Note the extra trip through utf-8 for quoted-printable, as it is not implemented in Python as a character encoding, but a byte encoding, so you cannot (safely) apply it to a unicode string. Jean-Paul From tjreedy at udel.edu Mon Mar 6 16:14:03 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 6 Mar 2006 16:14:03 -0500 Subject: Peter Naur wins ACM Turing Award Message-ID: http://campus.acm.org/public/pressroom/press_releases/3_2006/turing_3_01_2006.cfm Peter Naur was co-developer of Backus/Naur grammar notation, co-author and editor of the Algol 60 specification, and co-developer of a successful Algol compiler. Connection with Python: I believe Python owes more to the form and spirit of Algol than to any of the other early languages. Algol introduced the block structuring and, at least in practice, the indentation, that is a hallmark of Python. It was purposefully not tied to any particular architecture. It was "designed for communication among humans as well as with computers" even though human readability made compiler writing more challenging. Python: Algol for the 21st century? Terry Jan Reedy From Jue_Shi at or.mxim.com Fri Mar 24 17:18:38 2006 From: Jue_Shi at or.mxim.com (Shi, Jue) Date: Fri, 24 Mar 2006 14:18:38 -0800 Subject: Python C wrapper question Message-ID: <5C99C308457E6D4EA5448EA52A66004A084468F4@or.mxim.com> Hello, Gurus, I have a question on wrapping C function in Python. My C code is like this: typedef void (WINAPI *myCallBack) (unsigned int myarg1, unsigned int myarg2) bool myfunc(myCallBack callfunc) Now I want to call myfunc in Python, what should I do? Thanks, Stone From marek.rocki at wp.pl Sun Mar 5 17:13:21 2006 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: 5 Mar 2006 14:13:21 -0800 Subject: Adding method at runtime - problem with self Message-ID: <1141596801.544223.179570@e56g2000cwe.googlegroups.com> First of all, please don't flame me immediately. I did browse archives and didn't see any solution to my problem. Assume I want to add a method to an object at runtime. Yes, to an object, not a class - because changing a class would have global effects and I want to alter a particular object only. The following approach fails: class kla: x = 1 def foo(self): print self.x k = kla() k.foo = foo k.foo() I know where the problem is. The method shouldn't have 'self' parameter. But how do I access object's attributes without it? Best regards, Marek From steven.klass at gmail.com Thu Mar 9 20:22:12 2006 From: steven.klass at gmail.com (rh0dium) Date: 9 Mar 2006 17:22:12 -0800 Subject: Help with a reverse dictionary lookup In-Reply-To: References: <1141948280.743094.217230@j33g2000cwa.googlegroups.com> Message-ID: <1141953732.182782.137070@j33g2000cwa.googlegroups.com> Thanks!! I got all of this. The problem that I was trying to figure out was this. Basically there are multiple combinatories here - I was hoping someone could point me to a general approach. Writing the actual funtion is not necessary - as you pointed out I can certainly do that. Here is my problem - I did exactly as you and said OK I can if Foundry==None and Process==None: elif Foundy==None and Process!=None: elif Foundy!=None and Process==None: elif Foundy!=None and Process!=None: But this seems very ugly... And if I want to do this for the three areas, it seems very repetitive. I was looking for a better way to break this down which is reusable. Thanks for the help - I guess I should have been more clear. From http Sun Mar 19 14:17:08 2006 From: http (Paul Rubin) Date: 19 Mar 2006 11:17:08 -0800 Subject: Counting number of each item in a list. References: <1142772092.958602.272260@e56g2000cwe.googlegroups.com> <441d58f7$0$13046$626a54ce@news.free.fr> <1142774630.426660.19970@t31g2000cwb.googlegroups.com> <441d6342$1_3@newspeer2.tds.net> <441d9408$0$20430$636a55ce@news.free.fr> <441dab21$0$27059$626a54ce@news.free.fr> Message-ID: <7x8xr66y8b.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > And of course, I was right. My solution seems to be faster than Paul's > one (but slower than bearophile's), be it on small, medium or large > lists. > > nb: A is mine, B is Paul's and C is bearophile's, and the number after > is the size of the list... Interesting. I wonder if you could try it with a much larger number of distinct values in the list. From fredrik at pythonware.com Wed Mar 15 13:23:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Mar 2006 19:23:34 +0100 Subject: stdin or optional fileinput References: <1142439653.706305.134290@j33g2000cwa.googlegroups.com> Message-ID: "the.theorist" wrote: > I used this bit of code to detect wether i want stdinput or not. > > if len(args)==0: > args = [ sys.stdin ] > > Now in my main loop I've written: > > for file in args: > for line in open( file ): > #do stuff > > The probelm occurs when I pass no arguments and python trys to open( > sys.stdin ). > open() customarily accepts a pathname, and returns a file object. > But this code is so elegant I thought that maybe, if open were passed > file object it could re-open that file in a new mode (if a mode was > provided different from the current mode) or simply return the file > object it was passed. so use your own open function: def myopen(file): if isinstance(file, basestring): return open(file) return file for file in args: for line in myopen( file ): #do stuff or perhaps def myopen(file): if hasattr(file, "read"): return file return open(file) ... or perhaps if not args: args = [ "-" ] def myopen(file): if file == "-": return sys.stdin return open(file) for file in args: for line in myopen( file ): #do stuff (the "-" = stdin convention is quite common) From mailpitches at email.com Fri Mar 17 17:59:28 2006 From: mailpitches at email.com (mailpitches at email.com) Date: 17 Mar 2006 14:59:28 -0800 Subject: Python installation problem In-Reply-To: <1142635658.097143.261790@j52g2000cwj.googlegroups.com> References: <1142635658.097143.261790@j52g2000cwj.googlegroups.com> Message-ID: <1142636368.424234.66200@e56g2000cwe.googlegroups.com> Thanks for the fast responses.>mp From scott.daniels at acm.org Wed Mar 15 10:41:31 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 15 Mar 2006 07:41:31 -0800 Subject: Very, Very Green Python User In-Reply-To: <1142426368.211896.241540@e56g2000cwe.googlegroups.com> References: <1142215118.291132.130490@e56g2000cwe.googlegroups.com> <44159fb4$1@nntp0.pdx.net> <1142426368.211896.241540@e56g2000cwe.googlegroups.com> Message-ID: <4418337f$1@nntp0.pdx.net> hanumizzle at gmail.com wrote: > Scott David Daniels wrote: >> hanumizzle at gmail.com wrote: >>> ... Is the Python debugger fairly stable? >> Yes, but it is not massively featured. The "Pythonic" way is to >> rarely use a debugger (test first and straightforward code should >> lead to "shallow" bugs). Often for most of us judiciously placed >> print statements suffice. >> >> > The one you get with Perl stinks on ice. More than >>> anything else, I would like to have a powerful OO environment where I >>> do not have to worry about the debugger sucking .... >> Do watch your language on this newsgroup. Lots of people read this >> group and there is no good reason to offend them. In turn, you will be >> cut some slack. > > As one who avidly studies language, I have observed that the meaning of > a word slip out of its original context through idiomatic usage. If I > had included the implicit object of 'sucks', In fact I elided the "ass" from your original "sucks ass" in my original quote, and now you carefully forget it in order to bolster your case. > then you would have more grounds for complaint. However, 'sucks', > used in the intransitive sense, is no worse than 'bites the bag'. Comp.lang.python is an unusually well-mannered group. If you look at the messages over the past year (and exclude any chain with Xah Lee), I think you will find your language, while not obscene, was well below the standard for the newsgroup. Some of us value that, and are happy enough to leave it to other groups to express themselves more fervently. Here you'll find even strong disagreement is usually expressed with a careful consideration that the other person may well get offended. By the by, you will notice I did not simply chide you about your use of language, but rather answered your questions as best I understood them. Don't worry, this is the last I have to say on the subject. --Scott David Daniels scott.daniels at acm.org From florasol at hotmail.com Tue Mar 21 19:54:25 2006 From: florasol at hotmail.com (Francois) Date: 21 Mar 2006 16:54:25 -0800 Subject: NOT Python: Taxonomy list reference References: <44206b1f$1@nntp.zianet.com> <1142979944.805907.87290@v46g2000cwv.googlegroups.com> Message-ID: <1142988865.308299.196650@z34g2000cwc.googlegroups.com> This taxonomy is described in the Python Cookbook 2nd Ed,. Chapter 6, Introduction written by Alex Martelli, on page 234. The author explains that "multiple inheritance frees you from these contraints" - of fitting into a single taxonomy. From piet at cs.uu.nl Tue Mar 28 04:38:12 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 28 Mar 2006 11:38:12 +0200 Subject: How to inplement Session in CGI References: <1143525508.503801.54770@i39g2000cwa.googlegroups.com> Message-ID: >>>>> "Sullivan WxPyQtKinter" (SW) wrote: >SW> Python disappointly failed to provide a convinient cgi session >SW> management module. Not willing to use external modules, I would like to >SW> implement a simplest Session object on my own. >SW> The basic problem is: how could a python CGI program understand several >SW> requests are in the same session? Definately, request from different IP >SW> would be easy to identified to be in different sessions, but request >SW> from the same IP would not. http://starship.python.net/~davem/cgifaq/faqw.cgi?req=show&file=faq02.011.htp or google for python cgi session for more. But why write it yourself if someone else has already done the work? -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From wkehowski at cox.net Fri Mar 17 07:48:05 2006 From: wkehowski at cox.net (wkehowski at cox.net) Date: 17 Mar 2006 04:48:05 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: <1142589945.078364.32870@i39g2000cwa.googlegroups.com> References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1142589945.078364.32870@i39g2000cwa.googlegroups.com> Message-ID: <1142599685.186209.177630@j33g2000cwa.googlegroups.com> It would seem that your program is just filtering the full cartesian product, right? The solution I'm looking for generates the elements one-by-one so that it could be used in a loop. From i.g.j.v.d.sangen at student.tue.nl Mon Mar 20 06:10:26 2006 From: i.g.j.v.d.sangen at student.tue.nl (Ivo van der Sangen) Date: 20 Mar 2006 11:10:26 GMT Subject: Relative paths in mod_python References: <441dabfc$0$27059$626a54ce@news.free.fr> Message-ID: <441e8da2$0$27685$dbd4d001@news.wanadoo.nl> On 2006-03-19, Bruno Desthuilliers wrote: > Ivo van der Sangen a ?crit : >> I was wondering if I could use relative paths in a mod_python script. At >> the moment I am defining a constant string >> "/path/to/dir/where/script/resides". The problem with this is that when >> I move the script including files I use to get metadata I have to change >> this variable. The same problem occurs when I distribute the script; the >> person using it will first have to modify it, which is not what I want. Is >> it possible that a mod_python script has as current working directory >> the directory where the script resides? At the moment os.getcwd() >> returns '/'. > > You could set this constant in the apache conf as a PythonOption. And/Or > you could post this question to mod_python's mailing list !-) I wasn't aware of the mod_python list. The next time I will post my question there, but I don't think I will get a better answer there; the solutions given here so far are fine. From bdesth.quelquechose at free.quelquepart.fr Sun Mar 19 17:19:10 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 19 Mar 2006 23:19:10 +0100 Subject: Relative paths in mod_python In-Reply-To: References: Message-ID: <441dabfc$0$27059$626a54ce@news.free.fr> Ivo van der Sangen a ?crit : > I was wondering if I could use relative paths in a mod_python script. At > the moment I am defining a constant string > "/path/to/dir/where/script/resides". The problem with this is that when > I move the script including files I use to get metadata I have to change > this variable. The same problem occurs when I distribute the script; the > person using it will first have to modify it, which is not what I want. Is > it possible that a mod_python script has as current working directory > the directory where the script resides? At the moment os.getcwd() > returns '/'. You could set this constant in the apache conf as a PythonOption. And/Or you could post this question to mod_python's mailing list !-) From hgk at et.uni-magdeburg.de Wed Mar 15 10:13:36 2006 From: hgk at et.uni-magdeburg.de (Hans Georg Krauthaeuser) Date: Wed, 15 Mar 2006 16:13:36 +0100 Subject: FIR filtering In-Reply-To: <1142435176.837718.42220@v46g2000cwv.googlegroups.com> References: <1142428703.224948.317700@u72g2000cwu.googlegroups.com> <1142435176.837718.42220@v46g2000cwv.googlegroups.com> Message-ID: LabWINC wrote: > What's gnuradio? > http://www.gnu.org/software/gnuradio/ It's a c++ lib with a python wrapper. BTW, thats the first hit in google ... Hans Georg From caroundw5h at yahoo.com Sun Mar 26 21:47:12 2006 From: caroundw5h at yahoo.com (bitshadow) Date: 26 Mar 2006 18:47:12 -0800 Subject: How to learn python if I'm very familar with C++ References: <1143425213.085645.146410@u72g2000cwu.googlegroups.com> <1143427156.703223.257500@t31g2000cwb.googlegroups.com> Message-ID: <1143427632.184827.248060@i40g2000cwc.googlegroups.com> danmcleran at yahoo.com wrote: > >The book "Learning Python" worked for me (a long time C++ person). > > Me too. I programmed in nothing but C++ for years, but this book made > learning Python easy. there are tons of tutorials available on the web. if your familiar with C++ then the tutorial that comes with the latest download of the interpreter should be fine. for myself though i learned python with this book: http://apress.com/book/bookDisplay.html?bID=10013 From steve at hastings.org Mon Mar 27 01:01:49 2006 From: steve at hastings.org (Steve R. Hastings) Date: Sun, 26 Mar 2006 22:01:49 -0800 Subject: maximum() efficency References: Message-ID: On Mon, 27 Mar 2006 00:11:04 +0000, Paul McGuire wrote: > The doc string is not correct. The fault is mine, I'm afraid. I had thought I was copying that from an intact original version, but I must have edited it. I don't remember doing it, but I must have. To check, I went to Sourceforge and downloaded goopy again. Here, for the record, is the original Google maximum(): def maximum(cmp, lst): """maximum(cmp, lst) Returns the maximal element in non-empty list LST with elements compared via CMP() which should return values with the same semantics as Python's cmp(). If there are several maximal elements, the last one is returned. """ if not lst: raise ValueError, 'empty list' maxval = lst[0] for i in xrange(1, len(lst)): v = lst[i] if cmp(maxval, v) <= 0: maxval = v return maxval I apologize for the error. P.S. I'm happy to see that Google uses "lst" for a list. I do, too. I don't much like the convention of using "L" for a list, but I agree with Guido that using "l" is bad (looks too much like a one: "1"), so "lst" it is. I would have put the "cmp" argument second, and made it default to the built-in Python "cmp" function if not specified. Oh, well. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From tjreedy at udel.edu Wed Mar 15 23:07:47 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 15 Mar 2006 23:07:47 -0500 Subject: Clearing IE history References: <9583ed900603151309w60bd2625k7febe13b772dc9c8@mail.gmail.com> Message-ID: >I am trying to automate the clearing of IE history using python As far as I know, the history list is only kept in a 'history' directory and not in the registry. I have occasionally cleared it manually and it look cleared back in IE. On Win9x, it is somewhere under c:/windows (or whatever it was called). On XP, it is a per-user setting. tjr From jstroud at ucla.edu Mon Mar 6 15:18:10 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 06 Mar 2006 12:18:10 -0800 Subject: Python as an extension language In-Reply-To: <87r75f7rb3.fsf@wilson.homeunix.com> References: <871wxgq7q1.fsf@wilson.homeunix.com> <87r75f7rb3.fsf@wilson.homeunix.com> Message-ID: Torsten Bronger wrote: > Hall?chen! > > Sybren Stuvel writes: > > >>Torsten Bronger enlightened us with: >> >> >>>I already know how to do that in principle. My only concern is >>>distributing the thing, especially for the Windows platform. >> >>Check out distutils and py2exe. > > > I know that py2exe can convert a Python script into an EXE file, > however, I have no Python script. I only have C++ source code, and > I'd like to avoid saying, "well, please install my little EXE and > this 10MB Python MSI for scripting it". > > Tsch?, > Torsten. > Even if you had 30 different things to install to make your program work, you could bundle them into one double-clickable installer with inno setup. Usage is very easy. Also, read the FAQ and knowledge base entirely if you want to make pretty slick installers. Link: http://www.jrsoftware.org/isinfo.php James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From martin at v.loewis.de Sun Mar 19 10:11:09 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 19 Mar 2006 16:11:09 +0100 Subject: Python 2.5 Schedule In-Reply-To: <441d579f$0$25339$39db0f71@news.song.fi> References: <1142667600.257048.315910@z34g2000cwc.googlegroups.com> <441d579f$0$25339$39db0f71@news.song.fi> Message-ID: <441D748D.3070500@v.loewis.de> Pekka Niiranen wrote: > what I would like to see in (www.python.org) is > Windows installation package (*.msi) > compiled with option "--enable-unicode=ucs4". > See http://www.xml.com/pub/a/2005/06/15/py-xml.html Just enabling that option is not enough: the resulting binary likely crashes. In addition to changing the type of Py_UNICODE, you also need change all calls to Microsoft API that expects UCS-2 (i.e. all *W API). Contributions are welcome. Regards, Martin From wmmeyer at gmail.com Fri Mar 3 07:40:47 2006 From: wmmeyer at gmail.com (William Meyer) Date: Fri, 3 Mar 2006 12:40:47 +0000 (UTC) Subject: object's list index References: <1141388967.849854.239830@z34g2000cwc.googlegroups.com> Message-ID: Iain King gmail.com> writes: > what's wrong with: > > i = 0 > for object in list: > objectIndex = i > print objectIndex > i += 1 > > Iain > The issues with that is you might have a complex structure below the for object in list: with lots of continues or breaks and you don't want to have to remember to change the index everytime. There is an old pep (http://www.python.org/peps/pep-0212.html) that describes some proposed solutions, but I was wondering if anything has happened since aug 2000. I might just use the for objectIndex in range(len(list)): e = list[objectIndex] solution, though its ugly too. From http Wed Mar 15 04:41:16 2006 From: http (Paul Rubin) Date: 15 Mar 2006 01:41:16 -0800 Subject: SSL/TLS - am I doing it right? References: <1142240607.501914.4390@j52g2000cwj.googlegroups.com> <1142247180.180132.256110@v46g2000cwv.googlegroups.com> <1142252828.097230.36540@e56g2000cwe.googlegroups.com> <1142328759.640029.202910@j52g2000cwj.googlegroups.com> <7xy7zdnywx.fsf@ruckus.brouhaha.com> <1142338358.686906.226240@p10g2000cwp.googlegroups.com> Message-ID: <7xveugniyr.fsf@ruckus.brouhaha.com> "Frank Millman" writes: > > You also want to generate a client > > certificate to install on the server. > > Both you and Sybren are insistent that this is a necessary step, but I > confess I cannot see the need for it. The client is lightweight, and > authenticates itself to the server using a user id and password. What > is the worst that could go wrong? The client cert approach isn't strictly necessary but it means that the SSL stack takes care of stuff that your application would otherwise have to take care of at both the client and the server side. If you don't generate a certificate, you have to generate a username and password instead, and manage that. There's still secret authenticating info on the client, so you haven't really decreased the client's responsibility. Also, if you need to go to a heavier-duty approach sometime, there's an industry making hardware devices (e.g. smart cards) that encapsulate keys and certificates so that the keys are very difficult to get access to. That improves security considerably. From gherron at islandtraining.com Fri Mar 3 14:49:21 2006 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 03 Mar 2006 11:49:21 -0800 Subject: forcing exceptions In-Reply-To: <44089AE9.9070104@verizonwireless.com> References: <78E6A2FC276AD8428A8E2DBBB540855E03BFC559@NYOBGCEXMB21.uswin.ad.vzwcorp.com> <44089AE9.9070104@verizonwireless.com> Message-ID: <44089DC1.9020708@islandtraining.com> Bill Scherer wrote: >Nikola Skoric wrote: > > > >>Is there a way to tell the interpreter to display exceptions, even those >>which were captured with except? >> >> >> >I believe you are looking for "raise". >For example: > >Try: > some.code() >except SomeError: > do.whatever() > raise > > I don't think that's what was asked for. That will reraise the exception, but there is no guarantee that it will be displayed -- there may be further "except"s up stream to catch it. A traceback.print_exc() within the "except" clause will print it at that point, then execution can continue normally. Gary Herron > > >- Bill > > From peter.maas at somewhere.com Thu Mar 9 15:34:09 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Thu, 09 Mar 2006 21:34:09 +0100 Subject: convert hex to decimal In-Reply-To: <1141933631.455001.263320@z34g2000cwc.googlegroups.com> References: <1141933631.455001.263320@z34g2000cwc.googlegroups.com> Message-ID: challman at gmail.com schrieb: > popS = string.join(pop.readlines()) Why not popS = pop.read()? > The output from the second popen is: > > SNMPv2-SMI::enterprises.9.9.168.1.2.1.1.13.51858 = Hex-STRING: 00 00 00 > 26 > > > I need to get the Hex-STRING into the following format: 0.0038.. I know > how to covert 26 to 38 but I haven't figured out how to pad it or place Have look at ljust/rjust(width[, fillchar]) > the decimal point between the while number and the decimal. What's a while number? Peter Maas, Aachen From linuxnooby at yahoo.com.au Wed Mar 29 17:08:02 2006 From: linuxnooby at yahoo.com.au (linuxnooby at yahoo.com.au) Date: 29 Mar 2006 14:08:02 -0800 Subject: tkinter question In-Reply-To: References: <1143501305.697282.283180@t31g2000cwb.googlegroups.com> Message-ID: <1143670082.175804.317850@t31g2000cwb.googlegroups.com> Ultimately what I am trying to is create a public computer session manager. 1) User logs in and main application window is withdrawn (easy) 2) After (for example) 55 minutes - a warning window/dialoguebox "session will end in 5 minutes" 3) With 30 seconds to go - a warning window/dialoguebox "session will end in 30 seconds" 4) User logged out (easy) I am having problems with steps 2 and 3 Either the window/dialoguebox will (a) pause the program execution upon display waiting for user input or (b) both warnings display together when application has finished. What I want want is a window/dialogue box that will not halt application logic, and will display immediately. cheers David From nessus at mit.edu Wed Mar 8 16:58:07 2006 From: nessus at mit.edu (Douglas Alan) Date: Wed, 08 Mar 2006 16:58:07 -0500 Subject: Any advantage in LISPs having simpler grammars than Python? References: <1141770067.041526.292360@p10g2000cwp.googlegroups.com> <120s2eag21k9571@corp.supernews.com> <1141850350.191351.94750@p10g2000cwp.googlegroups.com> Message-ID: "Carl Banks" writes: > Douglas Alan wrote: > >> For instance, if Python were to have been designed so that you would >> write: >> >> let myVeryLongVariableName = 3 >> >> I would have preferred this over >> >> myVeryLongVariableName = 3 >> >> With the latter, I have to scan down the line to see that this line is >> in an assignment statement. > > Interesting. I always found that the visual distinctness of non-Lisp > programs made it easier to scan. For example, in Python I could blur my > eyes such that I can't positively identify the letters, but could still > tell an assignment from a function call from a mathemetical expression; > not so easy in LISP where expressions are visually similar. Hey, well I designed my own programming language "Drawl" that combines the best of both worlds. A sample program in Drawl would look something like this: proc mostApplicableMethods (g args) let appMethods = (filter [lambda (met) (mcProtoMetApp? met lex:args)] (funMets g)) let nMets = (len appMethods) if nMets = 1; appMethods elif nMets = 0; %{} else let retval = {} for i in (range nMets) let m1 = appMethods[i] for m2 in retval + appMethods[i+1..inf] if (isCongruentTo? m2 m1); break else (append list=retval ele=m1) retval This would correspond to the following Python code: def mostApplicableMethods(g, args): appMethods = filter(lambda met: isMcProtoMetApp(met, args), funMets(g)) nMets = len(appMethods) if nMets == 1: return appMethods elif nMets == 0: return () else: retval = [] for i in range(nMets): m1 = appMethods[i] for m2 in retval + appMethods[i+1:]: if isCongruentTo(m2, m1): break else: retval.append(m1) return retval In Drawl all expressions are either functions calls that begin with a "(" and are Lisp-like, or they are mathematical infix expressions. Statements and macros, on the other hand, always begin with an identifier that identifies the statement or macro. The exception to what I just said is that statements and macros can be turned into expressions by surrounding them with square brackets. Too bad I never got around to actually implementing Drawl, though, because we all know that what the world needs right now is another programming language.... |>oug From http Tue Mar 28 18:18:03 2006 From: http (Paul Rubin) Date: 28 Mar 2006 15:18:03 -0800 Subject: tips for this exercise? References: Message-ID: <7xy7yunopg.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Generally, lottery numbers are selected from a range, e.g. one to forty. > So rather than passing a global list, just pass the maximum number: > > def getNumbers(maxn=40): > L = range(1, maxn+1) > random.shuffle(L) > return L[0:5] Why is everyone using shuffle? 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 random >>> random.sample(xrange(1,41), 5) [24, 15, 9, 39, 19] From steve at REMOVETHIScyber.com.au Thu Mar 30 18:03:02 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 31 Mar 2006 09:03:02 +1000 Subject: any() and all() on empty list? References: <442B9AF7.2010407@REMOVEMEcyber.com.au> <7xu09gicko.fsf@ruckus.brouhaha.com> <442BAAA5.8010009@REMOVEMEcyber.com.au> <7xwtebpw95.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 30 Mar 2006 11:28:54 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> > No, all(seq) is true if you can't point to a specific element in seq >> > that's false. >> >> No, all(seq) is true if every element in seq is true. Surely that's a >> more intuitive definition than your definition by what you can't do. > > They are different? Of course they are different -- they differ in the case of an empty sequence. > I'd say every element in seq is true, unless > there's an element that's false. Do you want to pick a different word > than "all" and suggest renaming the function? I've already pointed out that I'm satisfied with Tim Peters' explanation for why the defined behaviour for any() is *most often* the Right Way for it to be implemented in Python, *but* there are circumstances that this behaviour is incorrect, therefore the programmer needs to actually consider carefully what should happen for the empty sequence case. Was I not clear enough? >> Here's another way of looking at the problem: >> >> all(flying elephants which are pink) => true >> all(flying elephants which are not pink) => true >> >> So, these flying elephants -- are they pink or not? > > By the definition, "all flying elephants are pink" and "all flying > elephants are non-pink" are both true statements, if that's what > you're asking. There is no contradiction. Of course there is a contradiction. The contradiction is that flying elephants are simultaneously pink and not pink. If you don't understand why "Foo is Bar" and "Foo is not Bar" can't both be true simultaneously, I suggest you spend some time googling on "noncontradiction logic". To get you started, here's the Wikipedia entry: http://en.wikipedia.org/wiki/Law_of_noncontradiction > It's one of those > questions like "have you stopped beating your wife". Think about it: what is the logical value of the boolean "I have stopped beating my wife" in the case of somebody who never started beating their wife? if husband.stopped_beating_wife(): # returns True or False pay_fine() else: go_to_jail() Pretty hard on the innocent husbands who never even beat their wife at all. What we're doing is running up to the limitations of Aristotelian two-value logic. We're trying to pigeon-hole answers into True/False that really don't fit, so of course there will be the occasional case where neither True nor False is correct. In hacker culture, the Chinese word "mu" (literally "without") is sometimes used to mean "I cannot answer that question because your assumptions are not correct". In the case of all(seq), the correct answer is "mu". But since we're stuck with binary logic, the more commonly useful behaviour is True, but sometimes that leads to problems, such as in my first example of Guido being punished because he was found guilty of all the terrorist crimes he committed -- which is an empty list. -- Steven. From oluoluolu at gmail.com Sat Mar 25 18:18:44 2006 From: oluoluolu at gmail.com (oluoluolu at gmail.com) Date: 25 Mar 2006 15:18:44 -0800 Subject: (not really) randon ideas References: <1143320266.676215.253250@j33g2000cwa.googlegroups.com> Message-ID: <1143328724.552828.61870@u72g2000cwu.googlegroups.com> regarding the constants, this is more for the "vm" (and type safety). actually enums, constants and symbols can prolly be implemented more or less the same. From rpdooling at gmail.com Wed Mar 29 16:24:30 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 29 Mar 2006 13:24:30 -0800 Subject: Try Python! References: <1143663801.542233.206500@u72g2000cwu.googlegroups.com> Message-ID: <1143667470.851465.284830@i39g2000cwa.googlegroups.com> Armin, Mike Meyer already took a crack at this, and his starts right up just by clicking on the link. http://www.mired.org/home/mwm/try_python/ Yours looks prettier, but I don't think novices are going to be able to figure out how to start it. Regards, rick From bearophileHUGS at lycos.com Mon Mar 6 12:14:20 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Mar 2006 09:14:20 -0800 Subject: Simulation Programming Skills and Python References: Message-ID: <1141665260.242322.153890@i40g2000cwc.googlegroups.com> Richard Blackwood: >Is the skill of being able to translate in one's head realworld relationships into a model represented by code an inherent/native skill of all programmers?< I don't think so. Creating a good computational model can be a complex art. >Python a good language for simulation programming?< It depends on the type of simulation. Python can be good to create a prototype of the simulation program, and it can be good if the simulation doesn't require much number crunching that cannot be vectorized :-) If the simulation require a lot of number crunching, but such operations can be done with Numarray and the like, then you can probably use Python or Mathematica, or similar systems. Otherwise you may need a hybrid program (Python + Pyrex, Swig, or f2py, ShedSkin, etc). Bye, bearophile From rbsharp at gmx.de Thu Mar 23 03:06:44 2006 From: rbsharp at gmx.de (rbsharp at gmx.de) Date: 23 Mar 2006 00:06:44 -0800 Subject: Using PyExcelerator In-Reply-To: <44221915$1@news.eftel.com> References: <1143064868.198835.45150@u72g2000cwu.googlegroups.com> <44221915$1@news.eftel.com> Message-ID: <1143101204.907595.251000@z34g2000cwc.googlegroups.com> I would agree with the author, pyExcelerator is good at writing Excel but xlrd is better at reading. I was recently forced to use them in tandem because pyExcelerator had problems reading an Excel sheet and xlrd had no problems. greetings, Richard Sharp John Machin wrote: > On 23/03/2006 9:01 AM, tkpmep at hotmail.com wrote: > > I have just installed PyExcelerator, and now want to use it to read > > Excel spreadsheets with a variable number of rows and columns and with > > multiple sheets. Unfortunately, no documentation seems to accompany > > PyExcelerator. Does anyone know of a good source of documentations > > and/or examples? The author provides some examples, but these tend to > > involve writing data into spreadsheets one cell at a time. > > > > Thomas, > Look at pyExcelerator's tools/xls2*.py for examples > or > Look at the xlrd package (which doesn't *write* xls files, but does read > them tolerably well -- even if I do say so myself -- and has documentation). > http://cheeseshop.python.org/pypi/xlrd > > What do you mean by "with a variable number of rows and columns"? > > Cheers, > John From lucaberto at libero.it Wed Mar 29 13:01:52 2006 From: lucaberto at libero.it (luca72) Date: 29 Mar 2006 10:01:52 -0800 Subject: excel application In-Reply-To: <1143647835.963572.270710@u72g2000cwu.googlegroups.com> References: <1143644666.914943.121390@i40g2000cwc.googlegroups.com> <1143647835.963572.270710@u72g2000cwu.googlegroups.com> Message-ID: <1143655312.408670.207010@u72g2000cwu.googlegroups.com> Thanks a lot Luciano Regards Luca From stefan.behnel-n05pAM at web.de Tue Mar 21 03:48:57 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 21 Mar 2006 09:48:57 +0100 Subject: How to fork or spawn processes to second processor ? In-Reply-To: <1142927804.719538@nbgm66x> References: <1142927804.719538@nbgm66x> Message-ID: <441fbdfa$0$21659$9b4e6d93@newsread2.arcor-online.net> Sabre wrote: > how can I spawn or fork a second process onto the second processor of my > dual core server ? Is there a possibility to determin the processor on which > a process shall run ? Hi, from your post it's not clear why you would want to do that or which operating system you are using. Normally, you can expect any decent multi-processor operating system to distribute the load nicely over all available processors. Relying on that might help you. Stefan From mensanator at aol.com Sun Mar 26 22:23:07 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 26 Mar 2006 19:23:07 -0800 Subject: a problem to solve References: <5oiUf.1818$No6.41433@news.tufts.edu> <1143237220.103038.52200@t31g2000cwb.googlegroups.com> Message-ID: <1143429786.985873.67040@i40g2000cwc.googlegroups.com> Clemens Hepper wrote: > Hi, > > mensanator at aol.com wrote: > > That's one way to do it. I did it that way because I have the > > hex patterns memorized. > > You should be able to generate your numbers like this: > > number = int('0010010001000000100', 2) Well, that would be another way, wouldn't it? Thanks for the tip, but you're a bit late (pun intended), we've both already solved the problem. And since base conversion is a one-way street in Python, the fact that you can do that doesn't eliminate the need for gmpy (or something equivalent) if you want to go the other way, decimal to binary. And furthermore, having Python's bitwise operators is nice, but it's not nice enough. I need the bitwise functionality gmpy provides that's not available in Python: scan for position of least significant 1 or 0, count of 1 bits, Hamming distance, etc. So, rather than point out that one can do number = int('0010010001000000100', 2) I would rather advise that the person obtain gmpy and use its conversion number = gmpy.mpz('0010010001000000100', 2) They'll thank me eventually. > > mfg > - eth From mtobis at gmail.com Sun Mar 5 13:56:29 2006 From: mtobis at gmail.com (Michael Tobis) Date: 5 Mar 2006 10:56:29 -0800 Subject: Python advocacy in scientific computation In-Reply-To: References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> Message-ID: <1141581744.431120.250640@i39g2000cwa.googlegroups.com> > $ rm `find . -name "*.pyc"` Ouch. Is that a true story? While we're remeniscing about bad typos and DEC, I should tell the story about the guy who clobberred his work because his English wasn't very strong. Under RT-11, all file management was handled by a program called PIP. For example to get a list of files in the current working directory you would enter PIP *.* /LI . Well this fellow, from one of those countries where our long "e" sound is their "i" sound, mournfully announced "I vanted a deerectory so I typed 'PIP *.* /DE' " That one is true. mt From nkammah at yahoo.fr Tue Mar 7 19:48:19 2006 From: nkammah at yahoo.fr (kepioo) Date: 7 Mar 2006 16:48:19 -0800 Subject: SAX/Python : read an xml from the end to the top In-Reply-To: References: <1141699735.555057.324540@p10g2000cwp.googlegroups.com> <474v65Fdv6vfU1@uni-berlin.de> <1141732681.385933.178960@v46g2000cwv.googlegroups.com> <1141743297.597655.261010@v46g2000cwv.googlegroups.com> Message-ID: <1141778899.230752.12710@u72g2000cwu.googlegroups.com> An example ( i changed the content to make it easier) : ################### input file ####################3 fruits 5 10 25 names vincent Robert open the car fruits 25 8 120 ##############################################3 The script I want to write has to track any change in the input file(what we want to track are parameters in the script. Here for instance, the number of apple and cherry). The ouput file for this example would be ( we write it as a stream): ################### OutPut file ################################# fruits 5 fruits 8 fruits 120 ############################################33333 The input file keeps being generated. The ouput file is generated on request. Both are streamed based : we happend to the end of the file. Any suggestion? From g.horvath at gmx.at Mon Mar 13 03:50:02 2006 From: g.horvath at gmx.at (Gregor Horvath) Date: Mon, 13 Mar 2006 09:50:02 +0100 Subject: __del__ not called? In-Reply-To: References: Message-ID: <84ee8$4415323b$506c2949$6059@news.chello.at> Duncan Booth schrieb: > What is less obvious is that new style classes always include circular > references, so a class is never detroyed until the garbage collector runs. Thanks. I tried the same example with old style classes and A.__del__ gets correctly called. > Of course, if your __del__ method actually does get invoked during program > exit you have to be pretty careful what you do: the chances are any global > variables you used in __del__ have already been destroyed in particular any > modules you imported may have been deleted. In short, don't rely on > anything much being possible from __del__ called this way. I wanted to close a database connection, which is opend by __init__. But what happens to my database connection (instance attributes of A) when __del__ is never called? -- Greg From ptmcg at austin.rr._bogus_.com Wed Mar 29 02:07:52 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 29 Mar 2006 07:07:52 GMT Subject: any() and all() on empty list? References: Message-ID: "Steve R. Hastings" wrote in message news:pan.2006.03.29.05.32.50.221097 at hastings.org... > So, Python 2.5 will have new any() and all() functions. > http://www.python.org/dev/peps/pep-0356/ > > > any(seq) returns True if any value in seq evaluates true, False otherwise. > > all(seq) returns True if all values in seq evaluate true, False otherwise. > > I have a question: what should these functions return when seq is an empty > list? > Here is my attempt at a more formal approach to this question, rather than just using our intuition. Unfortunately, following this process proves my earlier post to be wrong, but, oh well... Consider two sets A and B where A+B is the union of the two sets. if any(A+B) = True -> any(A) or any(B) = True but we cannot assert either any(A)=True or any(B)=True. if any(A+B) = False -> any(A) = False and any(B) = False. if all(A+B) = True -> all(A)=True and all(B)=True if all(A+B) = False -> all(A)=False or all(B)=False but we cannot assert either all(A)=False or all(B)=False. Now instead of B, lets add the empty set 0 to A. We want to come up logic such that adding the empty set does not change the values of all() or any(), since A+0=A. any(A+0) = any(A) or any(0) any(0) must be False, so that if any(A) is True, any(A+0) is True, and if any(A) is False, any(A+0) is False. all(A+0) = all(A) and all(0) if all(A) is True, all(A+0) is True. Therefore, all(0) is True. -- Paul From harlinseritt at yahoo.com Fri Mar 24 13:46:02 2006 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 24 Mar 2006 10:46:02 -0800 Subject: What's The Best Editor for python In-Reply-To: References: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> Message-ID: <1143225962.663512.80830@t31g2000cwb.googlegroups.com> Was actually going to throw in jEdit for the category of what's good on both platforms... For someone who despises Java, I actually like it. :-) Harlin From alan.franzoni.xyz at gmail.com Sat Mar 18 12:05:58 2006 From: alan.franzoni.xyz at gmail.com (Alan Franzoni) Date: Sat, 18 Mar 2006 18:05:58 +0100 Subject: __dict__ strangeness References: <482lr6Fhs1jvU1@individual.net> Message-ID: Georg Brandl on comp.lang.python said: >>>> d.__dict__ > {} Which Python version, on which system? I can see the properly inserted attribute in __dict__, both with old style and new style classes. -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Rremove .xyz from my address in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From plahey at alumni.caltech.edu Sun Mar 19 16:37:35 2006 From: plahey at alumni.caltech.edu (plahey at alumni.caltech.edu) Date: 19 Mar 2006 13:37:35 -0800 Subject: How to check if a directory is exist in python? In-Reply-To: <1142803465.164833.38160@j33g2000cwa.googlegroups.com> References: <1142803465.164833.38160@j33g2000cwa.googlegroups.com> Message-ID: <1142804255.293009.272330@t31g2000cwb.googlegroups.com> Check out os.path.isdir(path_name) http://docs.python.org/lib/module-os.path.html From steven.bethard at gmail.com Mon Mar 27 14:20:37 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 27 Mar 2006 12:20:37 -0700 Subject: New-style Python icons In-Reply-To: <44279790.7020708@jessikat.plus.net> References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> <44279790.7020708@jessikat.plus.net> Message-ID: <95adnfmzFo2dprXZnZ2dneKdnZydnZ2d@comcast.com> Robin Becker wrote: > Steven Bethard wrote: > ....... >>> >>> http://www.doxdesk.com/img/software/py/icons.zip >> >> I just wanted to say that I've been using these icons for almost a >> week now and I love them! I'd like to reiterate EuGeNe's request that >> these go into the Python 2.5 release if at all possible. >> >> STeVe > > Whilst admitting that my preference is purely old fogeyism, I prefer the > older icons. However, there is one aspect which seems to be forgotten. > These logos/icons are much more abstract and so harder to describe > verbally. It's pretty easy to describe the existing Python icons: "can > you see a green snake on your desktop?". How does one describe these new > icons? Can you see an icon with a blue and yellow plus on your desktop? ;) STeVe From utabintarbo at gmail.com Fri Mar 3 07:51:28 2006 From: utabintarbo at gmail.com (utabintarbo) Date: 3 Mar 2006 04:51:28 -0800 Subject: sockets, where can I find documentation? References: Message-ID: <1141390288.576918.193590@u72g2000cwu.googlegroups.com> For a good general book on networking with python, try Foundations of Python Network Programming by John Goerzen. http://www.amazon.com/gp/product/1590593715/qid=1141390241/sr=1-9/ref=sr_1_9/104-7194399-1227965?s=books&v=glance&n=283155 From skillet3232 at yahoo.com Mon Mar 27 02:51:35 2006 From: skillet3232 at yahoo.com (Skeets) Date: 26 Mar 2006 23:51:35 -0800 Subject: HIRING: PHP Developer In-Reply-To: <1143313877.802242.206050@i40g2000cwc.googlegroups.com> References: <1143313877.802242.206050@i40g2000cwc.googlegroups.com> Message-ID: <1143445895.912890.233430@t31g2000cwb.googlegroups.com> flash is over rated. rethink that requirement. From mailper at gmail.com Sun Mar 19 19:13:12 2006 From: mailper at gmail.com (Per) Date: 19 Mar 2006 16:13:12 -0800 Subject: Is there such an idiom? Message-ID: <1142813592.486643.111550@j33g2000cwa.googlegroups.com> http://jaynes.colorado.edu/PythonIdioms.html """Use dictionaries for searching, not lists. To find items in common between two lists, make the first into a dictionary and then look for items in the second in it. Searching a list for an item is linear-time, while searching a dict for an item is constant time. This can often let you reduce search time from quadratic to linear.""" Is this correct? s = [1,2,3,4,5...] t = [4,5,6,,8,...] how to find whether there is/are common item(s) between two list in linear-time? how to find the number of common items between two list in linear-time? From kent at kentsjohnson.com Thu Mar 30 11:20:27 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 30 Mar 2006 11:20:27 -0500 Subject: a hobbyist's dilemma In-Reply-To: References: <122nqan6hrb579a@corp.supernews.com> <1143732966.418068.226750@e56g2000cwe.googlegroups.com> Message-ID: <442c0013$1_1@newspeer2.tds.net> John Salerno wrote: > benchline wrote: > >>Since you want to learn to use python with a database you may want to >>try it with SQLite. > > The thing about mysql is that it's also the db used on my website, so I > figure it might be nice to learn that one in case I ever need to use > that db also. Unless the basic uses for all databases are the same (i.e. > if it isn't like learning a new language for each different database) Most of what you learn working with SQLite will apply to any relational database you use from Python - how to use DB-API and how to write SQL (or how to avoid writing SQL with SQLObject or SQLAlchemy). There are pesky differences in data types and how to pass parameters but the basics are the same. Kent From grante at visi.com Sat Mar 18 23:45:22 2006 From: grante at visi.com (Grant Edwards) Date: Sun, 19 Mar 2006 04:45:22 -0000 Subject: Can I use a conditional in a variable declaration? References: <1142741039.554379.182170@g10g2000cwb.googlegroups.com> Message-ID: <121pof2498r6dde@corp.supernews.com> On 2006-03-19, volcs0 at gmail.com wrote: > I want the equivalent of this: > > if a == "yes": > answer = "go ahead" > else: > answer = "stop" If that's what you want, then write that. ;) -- grante at visi.com Grant Edwards From joswig at corporate-world.lisp.de Mon Mar 20 15:25:22 2006 From: joswig at corporate-world.lisp.de (joswig at corporate-world.lisp.de) Date: 20 Mar 2006 12:25:22 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: <441ef3a2$0$15789$14726298@news.sunsite.dk> References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <441ef3a2$0$15789$14726298@news.sunsite.dk> Message-ID: <1142886321.996690.78600@t31g2000cwb.googlegroups.com> > I had a crack at it in Lisp. My version doesn't work - but of greater > concern to me is that it doesn't appear nearly as compact as the C > version. Anyway, here's my Lisp code (no prizes for guessing that I'm a > noob to Lisp): Lot's of things you can write more compact. But compact is not always the best way to write source. For me the most important criteria is that I can return to some source after, say, a year absence and everything is clear and readable again. > > (defconstant delta 2654435769 ) ; delta= 0x9E3779B9 (defconstant +delta+ #x9E3779B9) > (defun floorn (n) (nth-value 0 (floor n))) is above used? > (defun >> (val num-bytes) > "Right-shift positive integer val by num-bytes" > (let* (t1 t2) > (setf t1 (expt 2 num-bytes)) > (setf t2 (/ val t1)) > (floor t2))) (defun >> (val num-bytes) "Right-shift positive integer val by num-bytes" (floor (/ val (expt 2 num-bytes)))) > (defun transform (v1 v2 v3 v4) > (let (t1 t2 t3) > (setf t1 (<<4 v1)) > (setf t2 (expt v2 v1)) > (setf t3 (expt v3 (>> v2 5))) > (+ t1 t2 t3 v4))) > (defun transform (v1 v2 v3 v4) (+ (<<4 v1) (expt v2 v1) (expt v3 (>> v2 5)) v4)) and so on... From arkanes at gmail.com Tue Mar 28 21:34:03 2006 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 28 Mar 2006 20:34:03 -0600 Subject: python ctype question about "access violation reading location 0x5a5a5a5a" In-Reply-To: <20060329003836.88170.qmail@web52911.mail.yahoo.com> References: <20060329003836.88170.qmail@web52911.mail.yahoo.com> Message-ID: <4866bea60603281834x410839c9xe6c6bdad3bcabadc@mail.gmail.com> On 3/28/06, Yanping Zhang wrote: > Hi All, > > I need to use this C routine in python and there is a void pointer parameter in it: > (this routine was written by someone else): > > myfunc(int a, (void *)userdata, bool b) > > I saw someone in his C++ wrapper used this routine in this way: > myfunc(a, (void *)0x5a5a5a5a, b) > > In my python wrapper, I tried to call it as the following and both failed: > 1. myfunc(c_int(a), 0x5a5a5a5a, c_int(b)) > got error "access voilation reading from 0x5a5a5a5a" > 2. > data = 0x5a5a5a5a > mydata = c_void_p(data) > myfunc(c_int(a), mydata, c_int(b)) > same error as in 1 > > Can anyone know how to fix it? Thanks! > You are re-creating the C code correctly, the problem is that C code you're working from is wrong (and whoever wrote it should be beaten). Passing a constant like that as a pointer (that myfunc presumably does something with) is something that just can't work. > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > -- > http://mail.python.org/mailman/listinfo/python-list > From claird at lairds.us Fri Mar 17 11:08:03 2006 From: claird at lairds.us (Cameron Laird) Date: Fri, 17 Mar 2006 16:08:03 GMT Subject: accessing a USB HID References: <1142557118.268666.108770@e56g2000cwe.googlegroups.com> <1142562846.796988.277080@j33g2000cwa.googlegroups.com> Message-ID: In article <1142562846.796988.277080 at j33g2000cwa.googlegroups.com>, Serge Orlov wrote: >jodansmif at gmail.com wrote: . . . >> The obstacle our group currently faces is communicating with a >> microcontroller (ACS USB Servo II) that appears in Windows as a USD >> HID. Unfortunately, the vendor's sample code is in Visual Basic and >> Visual C++ which none of our group members have any experience using. >> >> My hope is that someone has experience with this type of problem and >> can point me to some reference material. At this point I'm a bit lost >> in the morass of USB terminology. >> >> While I'm at it... if anyone knows of a better way to approach this >> problem (serial or parallel microcontroller) or another language with >> better tools, I'd appreciate that as well. We're just trying to turn >> several motors on and off while polling some photodiodes and all this >> HID business seems like unnessary overkill. > >After cursory look at the device home page it appears the vendor is >providing an Active X control. So it looks like you will need to learn >client side COM programming no matter what language you choose. For >Python you will need win32 extensions: >http://starship.python.net/crew/mhammond/win32/Downloads.html >or you can use ActivePython distribution that comes integrated with it. > >Don't be scared by USB HID, it's just a mandatory classification of the >device under Windows, you don't need to deal with it. Python and COM >don't look scary: >http://www.python.org/windows/win32com/QuickStartClientCom.html > > -- Serge. > I'm sympathetic. The hardware manufacturers consistently produce manuals and documentation that ... puzzle me. However, Mr. Orlov is absolutely right: that it's exposed as an Active X control is good news. Working with COM through Python is fun and generally sensible. You should quickly find yourself able to write small, sensible code fragments that send signals to the motors and receive data from the photosensors. Good luck. From danbrwn at gmail.com Mon Mar 20 15:53:25 2006 From: danbrwn at gmail.com (danbrwn at gmail.com) Date: 20 Mar 2006 12:53:25 -0800 Subject: Win32 ActiveX with COM support In-Reply-To: <441f0ef5$0$20145$8fcfb975@news.wanadoo.fr> References: <1142866971.191129.313460@g10g2000cwb.googlegroups.com> <441f0ef5$0$20145$8fcfb975@news.wanadoo.fr> Message-ID: <1142888005.006916.45550@j33g2000cwa.googlegroups.com> How would the controls run within a web browser. Would the python interpreter automatically run after loaded into a browser? Also, the python controls would be text files? From rrr at ronadam.com Wed Mar 29 19:02:22 2006 From: rrr at ronadam.com (Ron Adam) Date: Wed, 29 Mar 2006 18:02:22 -0600 Subject: any() and all() on empty list? In-Reply-To: <7xy7ytmtk2.fsf@ruckus.brouhaha.com> References: <7x3bh1x0ym.fsf@ruckus.brouhaha.com> <42qWf.18211$uX5.7574@tornado.texas.rr.com> <7xzmj9u1di.fsf@ruckus.brouhaha.com> <85tWf.2748$Aa1.1605@dukeread05> <7xy7ytmtk2.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Ron Adam writes: >> Just thinking about things. I really just want what is best for >> Python in the long term and am not trying to be difficult. > > I'm sorry, maybe it's the math geek in me, but I just see all those > suggestions about "not not S" as being contorted. It's obvious to me > that all([]) should be True, that while(any(S)) should not terminate > if S is empty, etc. The 'not not S' is just a conversion to bool. Is the following less contorted to you? >>> bool([]) False > Someone asked for a cite; I listed one before: > > http://en.wikipedia.org/wiki/For_all > > See the "Negation" section. 'Is all True' isn't the same as 'Has all True'. As I said, I'm not questioning the mathematical meaning of the set relation 'is all True', but wondering weather or not an alternate relation 'has all True' would be better for use as a flow control test. Do you have some examples uses since it's obvious to you? We could all probably come up with examples that support either side. What I'm looking for are the obvious and common use examples. How would they behave differently depending on weather 'is all true' or 'has all true' is used? Which would be faster and simpler to use in most cases. I just have a feeling we will see a lot of "S and all(S)" expressions being used. Maybe that's not so bad, but I would prefer to not have to do that if it turns out to the standard idiom for all testing within a loop. The actual code used would be more efficient than my examples, they will have shortcutting behavior, and written in C. Those examples where meant to show the principle. And the question still stands: "Does it do the right thing in most situations it will be used in?" That will of course depend on weather it's being used as a mathematics test, or for flow control test. Which is why I suggested the possibly of having both. I believe the flow control semantics will be the more common use, but I may be mistaken thinking "S and all(S)" will be needed in most cases. This doesn't seem to be an issue for anyone else, so I'll wait and see how it turns out. Cheers, Ron From steve at holdenweb.com Sat Mar 18 06:51:20 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 18 Mar 2006 11:51:20 +0000 Subject: Is there no end to Python? In-Reply-To: <1142677667.002061.269760@p10g2000cwp.googlegroups.com> References: <1142622194.560240.4330@j52g2000cwj.googlegroups.com> <1142627765.683262.27120@i39g2000cwa.googlegroups.com> <1142677667.002061.269760@p10g2000cwp.googlegroups.com> Message-ID: kpp9c wrote: >>> This is good thing because I can ignore what I don't need. > > > I am finding that this is really not true for me. I find that if i use > other folks code, collaborate, or get help from other folks i still > have to know all the new constructs that i don't often use, and i > really struggle with iterators and generators and some of the newer > things and folks seem to have fallen in love with ridiculously complex > list comprehensions. (i'll admit i love the list comprehensions too, > but too a point) > > Don't get me wrong, i LOVE Python, but since 2.2 or so the language has > started to get some feature creep and is starting to evolve > exponentially fast and while all that pre 2.2 code is really readable > still, i see some stuff now that really really hurts my brain. We see > less silly lambdas than we used to, and Python is more powerful than > ever, but i think there has been a cost too. Python has become harder > to read and *MUCH* harder to learn all of a sudden. > > Personally i would like to see the core Python language evolve more > slowly and see work on packages, modules and DOCS!! > > but i am sure that is very much a minority opinion. I found the > language additions of 2.3 and 2.4 really hard to absorb. > > flame away... No need for flames. I'll content myself with pointing out that most 1.5.2 programs will run unchanged in 2.5, so the backwards compatibility picture is very good. Nobody makes you use the new features! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Mon Mar 13 08:53:49 2006 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Mon, 13 Mar 2006 14:53:49 +0100 Subject: mydate.strftime('%x') and cgi script Message-ID: <47lbrdFg58hmU1@news.dfncis.de> Hello, I'm writing a cgi script which only needs to run in a small LAN. I tried to show dates in a reasonable format by using import locale import datetime locale.setlocale(locale.LC_ALL, '') ... dt = datetime.date.today() print dt.strftime('%x') This works well in other scripts or at the interactive prompt. It doesn't work in a cgi script: in the browser the date is shown as 'mm/dd/yyyy' which is _not_ my 'Locale's appropriate date representation' as the documentation for strftime calls it. The workaround is simple: explicit description of the right format works ('%d.%m.%Y'). But why doesn't the short form work as well? Thank you for explanations or links to them, Koczian -- Dr. Sibylle Koczian Universitaetsbibliothek, Abt. Naturwiss. D-86135 Augsburg e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE From usenet-2004 at lithe.de Wed Mar 8 15:33:12 2006 From: usenet-2004 at lithe.de (Jan Niklas Fingerle) Date: 08 Mar 2006 20:33:12 GMT Subject: a question about zip... References: <1141849339.040283.213510@j33g2000cwa.googlegroups.com> Message-ID: <440f3f88$0$13798$9b4e6d93@newsread4.arcor-online.net> KraftDiner wrote: > [(0, 1), (2, 3), (4, 5), (6, 7)] > > Which is a list of tuples.. I wanted a tuple of tuples... >>> odd = (1,3,5,7) >>> even = (0,2,4,6) >>> all = zip(even, odd) >>> all [(0, 1), (2, 3), (4, 5), (6, 7)] >>> tuple(all) ((0, 1), (2, 3), (4, 5), (6, 7)) Cheers, --Jan Niklas From larry.bates at websafe.com Mon Mar 27 10:55:28 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 27 Mar 2006 09:55:28 -0600 Subject: COM server / COM client In-Reply-To: <1143473908.544188.52760@i40g2000cwc.googlegroups.com> References: <1143473908.544188.52760@i40g2000cwc.googlegroups.com> Message-ID: <44280AF0.1020205@websafe.com> Dan wrote: > Does the COM server created with python have to be compiled? I have the > need to integrate database access but, I can not have any proprietary > software. Meaning no compiled programs built by me. So, if python can > do com clients and servers without compiling, Im good. But I don't know > if that is possible. The ctypes example implies that it must be > compiled using py2exe. I know the clients don't have to be compiled. > What about the server? > Sounds like you are walking a "fine line" on the "no compiled programs written by me" thing. Py2exe doesn't REALLY compile python. Rather it PACKAGEs it into an .exe file with any required external routines in library.zip. With proper bundle option, you can put everything into the .exe file itself (except for mscvrt71.dll). Just makes it easier to distribute and you don't have to install Python. Using py2exe and Inno Setup (my recommendation) makes it easier to distribute your program to multiple computers. That said, no you don't have to compile. If you don't create .exe by using py2exe you must have Python on the machine and must set up any supporting libraries (like ctypes) in lib/site-packages. -Larry Bates From bencvt at gmail.com Tue Mar 21 21:17:34 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 21 Mar 2006 18:17:34 -0800 Subject: TypeError coercing to Unicode with field read from XML file In-Reply-To: <1142991689.520777.28860@v46g2000cwv.googlegroups.com> References: <1142991689.520777.28860@v46g2000cwv.googlegroups.com> Message-ID: <1142993854.836737.287070@u72g2000cwu.googlegroups.com> Randall Parker wrote: > My problem is that once I parse the file with minidom and a field from > it to another variable as shown with this line: > IPAddr = self.SocketSettingsObj.IPAddress > > I get this error: [...] > if TargetIPAddrList[0] <> "" and TargetIPPortList[0] <> > 0: > StillNeedSettings = False > > TestSettingsStore.SettingsDictionary['TargetIPAddr'] = > TargetIPAddrList[0] > > TestSettingsStore.SettingsDictionary['TargetIPPort'] = > TargetIPPortList[0] TargetIPAddrList[0] and TargetIPPortList[0] are *not* a string and an int, respectively. They're both DOM elements. If you want an int, you have to explicitly cast the variable as an int. Type matters in Python: >>> '0' == 0 False Back to your code: try a couple debugging print statements to see exactly what your variables are. The built-in type() function should help. To fix the problem, you need to dig a little deeper in the DOM, e.g.: addr = TargetIPAddrList[0].firstChild.nodeValue try: port = int(TargetIPPortList[0].firstChild.nodeValue) except ValueError: # safely handle invalid strings for int port = 0 if addr and port: StillNeedSettings = False TestSettingsStore.SettingsDictionary['TargetIPAddr'] = addr TestSettingsStore.SettingsDictionary['TargetIPPort'] = port --Ben From danmcleran at yahoo.com Thu Mar 9 10:56:55 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 9 Mar 2006 07:56:55 -0800 Subject: Is the standard output thread-safe? In-Reply-To: References: Message-ID: <1141919815.166485.60310@j33g2000cwa.googlegroups.com> >Is the standard output thread-safe? No. You'll need to synchronize access. From jukka.aho at iki.fi Tue Mar 14 09:36:49 2006 From: jukka.aho at iki.fi (Jukka Aho) Date: Tue, 14 Mar 2006 16:36:49 +0200 Subject: Customizing character set conversions with an error handler References: <1142199228.960882.74490@u72g2000cwu.googlegroups.com> Message-ID: Serge Orlov wrote: >> # So the question becomes: how can I make this work >> # in a graceful manner? > change the return statement with this code: > > return (substitution.encode(error.encoding,"practical").decode( > error.encoding), error.start+1) Thanks, that was a quite neat recursive solution. :) I wouldn't have thought of that. I ended up doing it without the recursion, by testing the individual problematic code points with .encode() within the handler, and catching the possible exceptions: --- 8< --- # This is our original problematic code point: c = error.object[error.start] while 1: # Search for a substitute code point in # our table: c = table.get(c) # If a substitute wasn't found, convert the original code # point into a hexadecimal string representation of itself # and exit the loop. if c == None: c = u"[U+%04x]" % ord(error.object[error.start]) break # A substitute was found, but we're not sure if it is OK # for for our target encoding. Let's check: try: c.encode(error.encoding,'strict') # No exception; everything was OK, we # can break off from the loop now break except UnicodeEncodeError: # The mapping that was found in the table was not # OK for the target encoding. Let's loop and try # again; there might be a better (more generic) # substitution in the chain waiting for us. pass --- 8< --- -- znark From eoinrogers at gmail.com Fri Mar 17 15:15:28 2006 From: eoinrogers at gmail.com (Byte) Date: 17 Mar 2006 12:15:28 -0800 Subject: Importing an output from another function Message-ID: <1142626528.204581.179350@v46g2000cwv.googlegroups.com> Probably a stupid question, but I'm a newbie and this really pisses me off. Run this script: import random def Func1(): choice = ('A', 'B', 'C') output = random.choice(choice) def Func2(): print output Func1() Func2() And: an error message...... It says: Traceback (most recent call last): File "ptls-demo.py", line 11, in ? Func2() File "how -the-hell-do-i-fix-this.py", line 8, in Func2 print output NameError: global name 'output' is not defined Obviosly, I need to import the variable 'output' from Func1() into Func2(), but how? Thanks in advance, -- /usr/bin/byte From plahey at alumni.caltech.edu Sun Mar 5 11:27:31 2006 From: plahey at alumni.caltech.edu (plahey at alumni.caltech.edu) Date: 5 Mar 2006 08:27:31 -0800 Subject: raw strings and \ In-Reply-To: References: <1141548565.145199.145910@e56g2000cwe.googlegroups.com> Message-ID: <1141576051.081203.318010@e56g2000cwe.googlegroups.com> Hi Duncan, thanks for the reply. I figured that this was a technical problem associated with the parser. This one is going on my Python gotchas list. It is really silly from an end user perspective to have \ not special in raw strings _except_ if it is the last character. From grflanagan at yahoo.co.uk Mon Mar 6 10:05:14 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 6 Mar 2006 07:05:14 -0800 Subject: a good algo to do this In-Reply-To: <1141649471.773627.257960@i40g2000cwc.googlegroups.com> References: <1141649471.773627.257960@i40g2000cwc.googlegroups.com> Message-ID: <1141657514.192478.211620@i40g2000cwc.googlegroups.com> eight02645999 at yahoo.com wrote: > hi > i need to do something like this > eg given a number (as a string) = "123" > there are a few combination i want to find with this string, ie > "132","321","231","312" and "213". so there are 6 combinations > altogether. i remember there's a formula for this, but forgot. Does > python have any modules/functions to do this? > > thanks factorial = [ 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000, 355687428096000, 6402373705728000 ] def permutation( iterable ): length = len(iterable) count = factorial[length] for i in range(count): sequence = list(iterable[:]) index = i N = count result = [] for j in range( length, 0, -1): N = N / j choice, index = index // N, index % N result += [ sequence.pop(choice) ] yield result a = [ ''.join(perm) for perm in permutation('123')] print a ['123', '132', '213', '231', '312', '321'] Gerard From daconti.mail at gmail.com Sun Mar 26 00:33:24 2006 From: daconti.mail at gmail.com (DrConti) Date: 25 Mar 2006 21:33:24 -0800 Subject: object references Message-ID: <1143351204.139672.36490@i39g2000cwa.googlegroups.com> Dear Python developer community, I'm quite new to Python, so perhaps my question is well known and the answer too. I need a variable alias ( what in other languages you would call "a pointer" (c) or "a reference" (perl)) I read some older mail articles and I found that the offcial position about that was that variable referencing wasn't implemented because it's considered bad style. There was also a suggestion to write a real problem where referencing is really needed. I have one...: I'm trying to generate dynamically class methods which works on predefined sets of object attributes. one of these is the set of attributes identfying uniquely the object (primary key). A na?ve attempt to do the job: class ObjectClass: """ Test primary Key assignment """ if __name__ == "__main__": ObjectClassInstantiated=ObjectClass() ObjectClassInstantiated.AnAttribute='First PK Elem' ObjectClassInstantiated.AnotherOne='Second PK Elem' ObjectClassInstantiated.Identifier=[] ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnAttribute) ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnotherOne) print ObjectClassInstantiated.Identifier ObjectClassInstantiated.AnAttribute='First PK Elem Changed' print ObjectClassInstantiated.Identifier leads a wrong result >./test.py ['First PK Elem', 'Second PK Elem'] ['First PK Elem', 'Second PK Elem'] --> wrong! It should write ['First PK Elem Changed', 'Second PK Elem'] i.e. the assgnment ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnAttribute) assigns only the attribute value, not the reference. so my question is: is it still true that there is no possibilty to get directly object references? Is there a solution for the problem above ? Thank you for any feedback and sorry for the long mail ...and the reference to perl :-) Regs, Davide From iclinux at gmail.com Mon Mar 13 22:49:32 2006 From: iclinux at gmail.com (iclinux) Date: 13 Mar 2006 19:49:32 -0800 Subject: how to get all users that currently logged in? Message-ID: <1142308172.816853.224140@j33g2000cwa.googlegroups.com> we can do it with 'who' in *nuix, but os.getlogin() returns only the user of the current process... how to do it by python, any suggestions? Best Regards. From pmartin at snakecard.com Sat Mar 25 12:43:51 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sat, 25 Mar 2006 11:43:51 -0600 Subject: image reduction script References: <%cUUf.2478$fS6.24@dukeread11> <44241E0D.80605@websafe.com> Message-ID: Larry, I actually did not find what I needed in PIL (missed it ?) but found this package quite usefull: http://www.imagemagick.org/script/index.php Philippe Larry Bates wrote: > Philippe Martin wrote: >> Hi, >> >> I need to write a script to reduce the resolution/color depth of an image >> (ex: .jpg) based on a target size. >> >> The point is for the target picture to still be "understandable" - yet I >> target getting down to 5K. >> >> Are there libraries out there that could help me start ? >> >> Thanks >> >> Philippe >> >> > Python Imaging Library (PIL). > > http://www.pythonware.com/products/pil/ > > -Larry Bates From duncan.booth at invalid.invalid Thu Mar 30 08:16:25 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Mar 2006 13:16:25 GMT Subject: Set Windows Environment Variable References: <1143723906.146263.136590@i40g2000cwc.googlegroups.com> Message-ID: Fuzzyman wrote: > Hello all, > > I would like to set a Windows Environment variable for another > (non-child) process. > > This means that the following *doesn't* work : :: > > os.environ['NAME'] = value > > In the ``win32api`` package there is a ``GetEnvironmentVariable`` > function, but no ``SetEnvironmentVariable``. Any options ? No, your only option is to find a solution which doesn't involve changing another process's environment. From p4sync at yahoo.com Tue Mar 21 01:02:21 2006 From: p4sync at yahoo.com (- C Saha -) Date: Mon, 20 Mar 2006 22:02:21 -0800 (PST) Subject: Code convertion from JSP to Python Message-ID: <20060321060221.94454.qmail@web34602.mail.mud.yahoo.com> Hi Python Veterans I need to convert a code from JSP (Java Tags are also there inside JSP) to PYTHON. I have OK kind of knowledge in PYTHON, but dont have a muck knowledge in JAVA/JSP. Any idea how to approach? Thanks in advance to all C Saha Thanks a lot to all in advance ==================== Thanks & Regards CSaha --------------------------------- Yahoo! Mail Bring photos to life! New PhotoMail makes sharing a breeze. -------------- next part -------------- An HTML attachment was scrubbed... URL: From siddharthdave84 at gmail.com Sun Mar 12 12:58:33 2006 From: siddharthdave84 at gmail.com (al pacino) Date: 12 Mar 2006 09:58:33 -0800 Subject: Python Love :) In-Reply-To: <1142152271.545155.268170@i40g2000cwc.googlegroups.com> References: <1142099350.122968.35220@i39g2000cwa.googlegroups.com> <1142152271.545155.268170@i40g2000cwc.googlegroups.com> Message-ID: <1142186313.502716.126710@z34g2000cwc.googlegroups.com> Paddy wrote: > Spread the love - tell your Java freinds :-) well said paddy ! :-)) From tjreedy at udel.edu Wed Mar 1 02:57:54 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 1 Mar 2006 02:57:54 -0500 Subject: Cross compile generation of .pyc from .py files... References: <1141176107.234667.93210@e56g2000cwe.googlegroups.com> Message-ID: wrote in message news:1141176107.234667.93210 at e56g2000cwe.googlegroups.com... > However we cannot figure out how to cross-compile the .py (of > distribution) files and > generate the .pyc files for the target ppc from an i686 system. Is it > possible to cross > compile .pyc files from .py files? I am under the impression that .pyc files are system independent. Have you tried simply copying them over? tjr From jedp at ilm.com Thu Mar 30 15:11:47 2006 From: jedp at ilm.com (Jed Parsons) Date: Thu, 30 Mar 2006 12:11:47 -0800 Subject: ldap usage In-Reply-To: References: Message-ID: <442C3B83.3020105@ilm.com> > Which LDAP server are you using? You can switch off this behaviour > with OpenLDAP. See man 5 slapd.conf, allow . I don't have anything other than user access. Good to know about this feature, though. You've been very helpful - I really appreciate it. Can you recommend any favorite books or sites where I can learn more about ldap? Many thanks, j Michael Str?der wrote: > Jed Parsons wrote: >> As an addendum, I discovered one little gotcha, namely that this: >> >> l.bind_s(username, password, ldap.AUTH_SIMPLE) >> >> throws an ldap.INVALID_CREDENTIALS error if the password contains the >> wrong text, but works if the password is empty. I guess this is >> tantamount to binding as ("", ""), but I wasn't expecting it; I figured >> if a username was specified, the password would have to agree. > > Yes, this is by design. Empty cred means just switching to anon > bind. LDAP was not intended to be used for password checking at that time. > > Which LDAP server are you using? You can switch off this behaviour with > OpenLDAP. See man 5 slapd.conf, allow . > >> So my >> little authentication example also needs to test for empty passwords. > > Yes! > > Ciao, Michael. -- Jed Parsons Industrial Light + Magic (415) 746-2974 grep(do{for(ord){(!$_&&print"$s\n")||(($O+=(($_-1)%6+1)and grep(vec($s,$O++,1)=1,1..int(($_-6*6-1)/6))))}},(split(//, "++,++2-27,280,481=1-7.1++2,800+++2,8310/1+4131+1++2,80\0. What!?"))); From s99999999s2003 at yahoo.com Wed Mar 15 21:13:25 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 15 Mar 2006 18:13:25 -0800 Subject: comparing huge files Message-ID: <1142475204.998414.213520@j52g2000cwj.googlegroups.com> hi i wrote some code to compare 2 files. One is the base file, the other file i got from somewhere. I need to compare this file against the base, eg base file abc def ghi eg another file abc def ghi jkl after compare , the base file will be overwritten with "jkl". Also both files tend to grow towards > 20MB .. Here is my code...using difflib. pat = re.compile(r'^\+') ## i want to get rid of the '+' from the difflib output... def difference(filename,basename): import difflib base = open(basename) a = base.readlines() input = open(filename) b = input.readlines() d = difflib.Differ() diff = list(d.compare(a, b)) if len(diff) > 0: os.remove(basename) o = open(basename, "aU") for i in diff: if pat.search(i): i = i.lstrip("\+ ") o.writelines(i) ## write a new base file... o.close() g = open(basename) return g.readlines() Whenever the 2 files get very large, i find that it's very slow comparing...any good advice to speed things up.? I thought of removing readlines() method, and use line by line compare. Is it a better way? thanks From johnjsal at NOSPAMgmail.com Mon Mar 6 10:03:00 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 06 Mar 2006 15:03:00 GMT Subject: slicing the end of a string in a list In-Reply-To: <7xoe0o13kt.fsf@ruckus.brouhaha.com> References: <1141357052.436244.24670@i39g2000cwa.googlegroups.com> <7xy7zs88xq.fsf@ruckus.brouhaha.com> <7xoe0o13kt.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > John Salerno writes: >> Interesting. So I would say: >> >> [line.rstrip() for line in open('C:\\switches.txt')] How would I manually close a file that's been opened this way? Or is it not possible in this case? Is it necessary? From martin at v.loewis.de Sat Mar 25 08:31:04 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 25 Mar 2006 14:31:04 +0100 Subject: encoding problems =?ISO-8859-1?Q?=28=E9_and_=E8=29?= In-Reply-To: <1143260660.598726.269990@i39g2000cwa.googlegroups.com> References: <442378fa$1@news.eftel.com> <44247837.10305@v.loewis.de> <1143260660.598726.269990@i39g2000cwa.googlegroups.com> Message-ID: <44254618.3010203@v.loewis.de> Serge Orlov wrote: > The problem is that U+0587 is a ligature in Western Armenian dialect > (hy locale) and a character in Eastern Armenian dialect (hy_AM locale). > It is strange the code point is marked as compatibility char. It either > mistake or political decision. It used to be a ligature before > orthographic reform in 1930s by communist government in Armenia, then > it became a character, but after end of Soviet Union (1991) they > started to think about going back to old orthography. Though it hasn't > happened and it's not clear if it will ever happen. So U+0587 is a > character. Thanks for the explanation. Without any knowledge, I would suspect a combination of mistake and political decision. The Unicode consortium (and ISO) always uses native language experts to come up with character definitions, although the process is today likely more elaborate and precise than in the early days. Likely, the Unicode consortium found somebody speaking the Western Armenian dialect (given that many of these speakers live in North America today); the decision might have been a mixture of lack of knowledge, ignorance, and perhaps even political bias. Regards, Martin From kp8 at mac.com Mon Mar 13 23:19:34 2006 From: kp8 at mac.com (kpp9c) Date: 13 Mar 2006 20:19:34 -0800 Subject: markov query Message-ID: <1142309974.440477.192600@u72g2000cwu.googlegroups.com> markov query I have noticed a couple markov implementations in python, but none quite seem to do what i would like. Most seem to do an analysis of some text and create a new text based on that... I think, (sorry i just don't know terminology well) a markov table (or is it called a transition table) to describe how to get from one event to another. So if i have 3 events, say, A, B, and C which can come in any order, a Markov chain describes the probability of what the next event will be using a table. The following table demonstrates a first-order Markov chain. There are three possible states. Either the current event is A, B, or C. For each possible current state, there are three possible next letters. Each row in the table indicates the relative probability of going to the next letter. For example, if you are currently on letter A, there is a 20% chance of repeating letter A, a 50% chance of going to B, and a 30% chance of going to C. Note that the sum of changes for each row is 100% (20 + 50 + 30 = 100). Current -- next -- next -- next A ----- B ----- C A: 20% -- 50% -- 30% B: 35% -- 25% -- 40% C: 70% -- 14% -- 16% Here the sequence C B and C C would be rare and the sequence C A common. This is a first-order Markov chain, which means that only the current state affects the choice of the next event. A second-order Markov chain would mean that the current state and the last state affect the choice of the next event. A third-order Markov chain would indicate that the current state and the last two states in the sequence will affect the choice of the next state, and so on. Here is an example transition table for a 2nd order Markov chain. Current -- next -- next -- next A ----- B ----- C A A 15% 55% 30% A B 20% 45% 35% A C 60% 30% 10% B A 35% 25% 40% B B 49% 48% 3% B C 60% 20% 20% C A 5% 75% 20% C B 0% 90% 10% C C 70% 14% 16% For example, if the current event is B and the last one was A, then the probability of the next event being A is 20%, B is 45% and C is 35%. The pattern C B A will never occur, and the pattern B B C will occur rarely. Does anyone know of any modules or packages that include markov tables for creating patterns like shown above. P.S. Does any one know first of all whether these are called markov tables, transition tables or probability tables? I am not sure i am referring to this correctly and what the differences would be if any cheers, kp From mcPas.De.Spam at mclaveauPas.De.Spam.com Sat Mar 4 02:19:35 2006 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Sat, 04 Mar 2006 08:19:35 +0100 Subject: Win32api, pyHook, possibly win32com, not sure XD, thats why I'm posting References: <1141435919.954008.241240@t39g2000cwt.googlegroups.com> Message-ID: Hi! Rename Pythonw.exe like jtp.exe And... run: jtp.exe yourscript.pyw -- @-salutations Michel Claveau From apgwoz at gmail.com Thu Mar 9 10:04:53 2006 From: apgwoz at gmail.com (Andrew Gwozdziewycz) Date: Thu, 9 Mar 2006 10:04:53 -0500 Subject: Python Evangelism In-Reply-To: References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> Message-ID: <8ba244fb0603090704k616b4d41jeb1e125acbd6e95a@mail.gmail.com> On 3/9/06, rtilley wrote: > > Doug Bromley wrote: > >> I can see Ruby overtaking Python if we don't ALL do something about it. > > I think it's the name. Python. Let's change it to something nicer. Think > about it... if you found a Ruby, you'd pick it up and put it in your > pocket. If you ran across a Python, you'd run away. Woah, are you actually serious? What would changing the name of language you're trying to market do for the marketing campaign? New to the YAMMA language? Check out all these other Python tutorials to get started. I don't think it's the name, I think the major problem is people saying, "What can we do to market it?" and not actually doing anything, as Steven just said. Work on something. Create something popular. Heck promote django or some other framework. Work on some new innovative technology in python! Just choose python and recommend it to others. Word of mouth, Quality projects and not claiming "we need new marketing strategies" _IS_ the best marketing strategy. > Gems is nice too. Compare that to Cheese Shop... who came up with that > :) Do you want a pretty gem stone or a smelly slice of cheese? I mean > that in a literal sense. I don't think Python is smelly at all, but it > certainly has chosen some slimy, smelly bad names for itself! While I agree, that gem is nice and python needs a new standard package management system, maybe that's your contribution! Build it! Make it awesome! > Psychology is important. Just as important as good design. I think this > fact doesn't sink in to the Python community. Pyschology _is_ important, but not in this case. Make good products and they will come. Python has a ton of good projects and a ton of users. What we don't have is ruby on rails and the web 2.0 crowd, and I say, who the hell cares? We have everything else. -- Andrew Gwozdziewycz http://ihadagreatview.org http://plasticandroid.org From jstroud at ucla.edu Wed Mar 8 20:03:03 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 08 Mar 2006 17:03:03 -0800 Subject: question about slicing with a step length In-Reply-To: References: Message-ID: John Salerno wrote: > Given: > > numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > can someone explain to me why > > numbers[10:0:-2] results in [10, 8, 6, 4, 2]? > > I thought the first index, whether going forward or backward, was > inclusive. And there is no index of 10 in this list, so what is it > referring to? > > Thanks. Its referring to right after the end of the list, just as the 0 refers to just before the start of the list. The word "slice" is supposed to suggest cutting between (or before or after) elements. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From andrew at trevorrow.com Thu Mar 9 05:37:34 2006 From: andrew at trevorrow.com (Andrew Trevorrow) Date: Thu, 9 Mar 2006 21:37:34 +1100 Subject: embedding Python: how to avoid memory leaks? Message-ID: No response to my last message, so I'll try a different tack... Does anyone know of, or even better, has anyone here written a C++ application for Mac/Windows that allows users to run Python scripts from within the app? Not just once, but many times in a single session, and without leaking memory. Preferably an open source app so I can see how it's done. Our app (http://golly.sourceforge.net/) currently uses calls like these every time a user decides to run a script: Py_Initialize(); PyRun_SimpleString("execfile('foo.py')"); Py_Finalize(); But even if foo.py is *empty* the above calls result in a memory leak of about 12K on Mac OS 10.3.9 (using Python 2.3) and about 11K on Windows 2000 (using Python 2.4.2). I wouldn't mind if there was a one-off cost due to calling Py_Initialize the very first time, but we see leaks every time a script is executed. I've tried calling Py_Initialize just once (at app startup) and Py_Finalize once on exit, but that doesn't really solve anything. It avoids leaks when using trivial scripts (like an empty .py file!) but we want to run some rather complicated scripts that consume lots of memory, so we need a reliable way to release that memory. I was surprised to discover that Py_Finalize doesn't always do that. Is there some magic Python code that can restore memory usage to what it was before each execfile call? Something like PostScript's save and restore. I've been struggling with this problem for about a week now. Having been seduced by Python's power and beauty I'd hate to have to abandon it and switch to Perl or some other crappy scripting language! Please help... Andrew From petr at tpc.cz Sat Mar 4 17:52:27 2006 From: petr at tpc.cz (Petr Jakes) Date: 4 Mar 2006 14:52:27 -0800 Subject: spliting on ":" In-Reply-To: References: <1141491273.776287.66070@j33g2000cwa.googlegroups.com> Message-ID: <1141512747.397241.61000@i40g2000cwc.googlegroups.com> > I think you're getting caught by the classic and/or trap in Python, > trying to avoid using a simple if statement. What do you mean by "the classic and/or trap"? Can you give an example please? Petr Jakes From timr at probo.com Tue Mar 21 02:02:37 2006 From: timr at probo.com (Tim Roberts) Date: Tue, 21 Mar 2006 07:02:37 GMT Subject: Xah's Edu Corner: The Concepts and Confusions of Pre-fix, In-fix, Post-fix and Fully Functional Notations References: <1142490052.127055.50130@v46g2000cwv.googlegroups.com> <1142585935.934786.115700@e56g2000cwe.googlegroups.com> <47fp121h8splgjgifoo26m5gqrr5octii3@4ax.com> <21op12hmneklbsogjv3m4fl4lnvp12f4h4@4ax.com> Message-ID: Roedy Green wrote: >On Sun, 19 Mar 2006 02:08:11 GMT, Tim Roberts wrote, >quoted or indirectly quoted someone who said : > >>Try pressing Ctrl-R when his message is visible. I'm also using Agent, and >>that toggles his extended characters from quoted-printable to visible for >>me. > >that swaps fixed and variable pitch fonts. I gather you have one of >your fonts configured without many chars in it. Not in Agent 3. In Agent 3, Ctrl-R toggles between "Display as Plain Text" and "Display as Raw Message". One of the two shows quoted-printable characters as =E3=D2=89, and the other interprets them based on the character set in the message header. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From adelagon at gmail.com Tue Mar 28 08:31:44 2006 From: adelagon at gmail.com (Alvin A. Delagon) Date: Tue, 28 Mar 2006 13:31:44 +0000 Subject: Obtaining the remote ip address Message-ID: <44293AC0.9000806@gmail.com> One quick question: I have a python cgi script running behind a CGI server which is also built using python using CGIHTTPServer module. How can my cgi script obtain the remote ip address? From mateom at gmail.com Thu Mar 16 13:20:37 2006 From: mateom at gmail.com (mateom at gmail.com) Date: 16 Mar 2006 10:20:37 -0800 Subject: Queue limitations? References: <1142440071.355627.120450@z34g2000cwc.googlegroups.com> <1142465843.868558.62750@e56g2000cwe.googlegroups.com> Message-ID: <1142533237.306662.288810@p10g2000cwp.googlegroups.com> I am creating the images by reading from texture memory using glGetTexImage(). As an experiment, I tried calling glGetTexImage() only once and letting imagQueue use that same reference over and over, but the images were all the same. So, this leads me to believe that the references returned by glGetTexImage() are to unique buffers, right? ( documentation for glGetTexImage() doesn't seem to disagree ) Perhaps, as an OpenGL program, something strange is happening with the references when my producer method goes out of scope. I guess for now I can be content to just pass immutable types across the thread boundary. From anand.chittu at gmail.com Thu Mar 23 00:13:06 2006 From: anand.chittu at gmail.com (Anand) Date: 22 Mar 2006 21:13:06 -0800 Subject: multiple assignment In-Reply-To: References: <1143018514.721434.246450@i39g2000cwa.googlegroups.com> <1143039628.881127.25010@u72g2000cwu.googlegroups.com> Message-ID: <1143090786.649093.114960@g10g2000cwb.googlegroups.com> >> Wouldn't it be nice to say >> id, *tokens = line.split(',') > > > id, tokens_str = line.split(',', 1) But then you have to split tokens_str again. id, tokens_str = line.split(',', 1) tokens = tokens_str.split(',') this is too verbose. anand From rdh at new.rr.com Wed Mar 22 12:17:20 2006 From: rdh at new.rr.com (DataSmash) Date: 22 Mar 2006 09:17:20 -0800 Subject: import random module References: <1143046086.771003.43180@g10g2000cwb.googlegroups.com> <1143046848.154484.124700@j33g2000cwa.googlegroups.com> Message-ID: <1143047840.122311.42030@i40g2000cwc.googlegroups.com> Much Thanks! I deleted the random.pyc and renamed the script and everything is good! R.D. From johnjsal at NOSPAMgmail.com Thu Mar 2 14:16:04 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 02 Mar 2006 19:16:04 GMT Subject: how do you move to a new line in your text editor? In-Reply-To: <1141326582.490436.125810@j33g2000cwa.googlegroups.com> References: <%ZGNf.1711$No6.40016@news.tufts.edu> <1141325510.264691.215260@t39g2000cwt.googlegroups.com> <1141326582.490436.125810@j33g2000cwa.googlegroups.com> Message-ID: Carl Banks wrote: > You wouldn't know if Ultraedit has some kind of hook mechanism (whereby > it can execute a macro or script or something upon loading/saving). > That could solve your problem. Obviously, having to manually convert > isn't too helpful. I'll have to check on that. I know I can do macros and such, but I'll have to see about having it done automatically. From Christopher.Duffy at comcast.net Sat Mar 11 11:40:00 2006 From: Christopher.Duffy at comcast.net (Spinchange) Date: 11 Mar 2006 08:40:00 -0800 Subject: Old Python Logo Message-ID: <1142095200.056208.83360@j52g2000cwj.googlegroups.com> Can someone post a link or email me an image of the old Python logo? I'd like to save a copy of it, I rather liked it - very retro. From python-url at phaseit.net Fri Mar 17 18:08:03 2006 From: python-url at phaseit.net (Cameron Laird) Date: Fri, 17 Mar 2006 23:08:03 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 17) Message-ID: QOTW: "Generally, you should always go for whatever is clearest/most easily read (not just in Python, but in all languages)." - Timothy Delaney "You will find as your programming experience increases that the different languages you learn are appropriate for different purposes, and have different advantages and disadvantages. Python excels at expressing algorithms in an unambiguous and easily-readable way." - Steve Holden Is Python a viable extension language for Java? Ravi Teja expertly outlines the possibilities: http://groups.google.com/group/comp.lang.python/msg/54ad155bc138c8d2 "In order to facilitate small groups working on specific Python-in-Education projects, we have launched an edupython list on google groups." This is a hands-on complement to the more "philosophical" edu-sig. http://groups.google.com/group/edupython mailto:edupython at googlegroups.com One interesting use of Python--at least to software workers--is to manage texts written in *other* languages. Fredrik Lundh and Roman Yakovenko present good approaches for the C++ case: http://groups.google.com/group/comp.lang.python/msg/913eb2563b815745 http://groups.google.com/group/comp.lang.python/msg/2b74c8355fc5c25a Pascal and Python? Sure: http://groups.google.com/group/comp.lang.python/browse_thread/thread/9806ed054493d6a6/ Uche Ogbuji details XPath, *XSLT, XQuery, ... capabilities: http://groups.google.com/group/comp.lang.python/browse_thread/thread/51b0fcdc7df8a34e/ ======================================================================== 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 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://python.sourceforge.net/peps/pep-0042.html 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 ruby at no.spam Fri Mar 10 12:01:16 2006 From: ruby at no.spam (Michal Kwiatkowski) Date: Fri, 10 Mar 2006 18:01:16 +0100 Subject: Why property works only for objects? In-Reply-To: <1hbyfgj.a3p39r1smomavN%aleaxit@yahoo.com> References: <1hbyfgj.a3p39r1smomavN%aleaxit@yahoo.com> Message-ID: Alex Martelli napisa?(a): > Wrong! Of _course_ it's an option -- why do you think it matters at all > whether you're the creator of this object?! Statically typed languages background. Sorry. ;) >> Code below doesn't work, but shows my >> intention: >> >> # obj is instance of BaseClass >> def get_x(self): >> # ... >> def set_x(self, value): >> # ... >> obj.x = property(get_x, set_x) > > def insert_property(obj, name, getter, setter): > class sub(obj.__class__): pass > setattr(sub, name, property(getter, setter)) > obj.__class__ = sub > > See? Of COURSE you can subclass -- not hard at all, really. Let me understand it clearly. If I change __class__ of an object, existing attributes (so methods as well) of an object are still accessible the same way and don't change its values. Only resolution of attributes/methods not found in object is changed, as it uses new version of __class__ to lookup names. Is this right? 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 grahamd at dscpl.com.au Fri Mar 24 21:32:09 2006 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 24 Mar 2006 18:32:09 -0800 Subject: Caching in memory for Apache References: <1143212200.835484.324420@i39g2000cwa.googlegroups.com> Message-ID: <1143253929.381048.97440@z34g2000cwc.googlegroups.com> Simon Johnson wrote: > Dear All, > > I have decided to take the big plunge and drop the Microsoft platform > and use Mod_Python and Apache in it's place. > > I've never used Linux before this project so it's a really big learning > curve, but so far it's going well. I've managed to create some simple > pages using the basic of Python. > > One of the questions I have is: How do you cache stuff in memory? Say > I've got a bunch of stuff I need to create from a set of database rows. > Obviously, I do not want to consult the database each time I have a > request for my page. Is there anyway in Mod_python for me to store > values inside memory so I can look it up on the next GET request? It all depends a bit on what you want to cache and whether the data is specific to one users interaction with a page, or whether the data is able to be used across requests from multiple users. This will dictate whether you can use a global data cached within modules used to generate the page, whether you can use sessions, shared memory or whether you have no choice but to always go back to the database. As others have pointed out, don't get trapped in doing premature optimisation. More often than not what you may think will be a bottle neck will not and any problems if they even exist will be elsewhere. In respect of mod_python, it is also vitally important to understand the process/interpreter module under which Python runs within the context of Apache. A starting point for getting information about this is: http://www.dscpl.com.au/articles/modpython-004.html If you do decide that sessions may be useful to what you are doing, as pointed out by others, there can be limitations as to what data can be stored. For limitations in respect of sessions in mod_python have a look at: http://www.dscpl.com.au/articles/modpython-005.html Finally, make sure you use the latest version of mod_python available. Avoid using mod_python 2.7.X or 3.1.X as there are lots of known issues and problems. Not all problems are solved in 3.2.X version, but good progress has been made on getting rid of many issues. The main area which can still cause problems, especially when trying to cache data in the Apache process, is that of module loading and reloading. For a run down on issues in that area see: http://www.dscpl.com.au/articles/modpython-003.html A lot of work has already been done on solving these issues for 3.3.X version of mod_python. BTW, the best place to ask questions about mod_python is the mod_python mailing list. Thus, get yourself subscribed to it. Details of the mailing list are on the mod_python web site. Graham From goofyheadedpunk at gmail.com Thu Mar 9 07:23:37 2006 From: goofyheadedpunk at gmail.com (Brian L. Troutwine) Date: 9 Mar 2006 04:23:37 -0800 Subject: grayscale pixel based graphics with pygame In-Reply-To: References: <1141872392.131004.247580@v46g2000cwv.googlegroups.com> Message-ID: <1141907017.650326.37270@v46g2000cwv.googlegroups.com> Geez, I apologize for my post being so vague. I was terribly tired when I wrote that, and should have known better than to post. I was not aware of the pygame mailing list. I will take this question there. From deets at nospam.web.de Fri Mar 10 19:55:30 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 11 Mar 2006 01:55:30 +0100 Subject: Performance impact of using decorators In-Reply-To: <1142010742.702301.281760@z34g2000cwc.googlegroups.com> References: <1142003515.886709.290360@j33g2000cwa.googlegroups.com> <1142008926.296541.111550@j52g2000cwj.googlegroups.com> <47dpc0Feqo2pU1@uni-berlin.de> <1142010742.702301.281760@z34g2000cwc.googlegroups.com> Message-ID: <47elg1Ff8tfcU2@uni-berlin.de> vinjvinj schrieb: >>> That sounds like something for the templating engine, and _certainly_ not >>> for a decorator that otherwise deals with transactions. > > The actual code for the page layout is in a preppy template. But the > calls to the template engine are made in the > startTransactrionAndBuildPage decorator Well, even if it would fit in a decorator - it certainly belongs to its _own_ decorator. Diez From iddw at hotmail.com Mon Mar 20 19:06:29 2006 From: iddw at hotmail.com (Dave Hansen) Date: Mon, 20 Mar 2006 18:06:29 -0600 Subject: Function params with **? what do these mean? References: <1142887602.977736.300990@u72g2000cwu.googlegroups.com> Message-ID: On 20 Mar 2006 15:45:36 -0800 in comp.lang.python, aahz at pythoncraft.com (Aahz) wrote: >In article , >Dave Hansen wrote: [...] >>It's harder to explain than understand. Try playing with the >>following function in the python interpreter: >> >> def test(a,b='b', *c, **d): >> print a,b,c,d > >Personally, I think it's a Good Idea to stick with the semi-standard >names of *args and **kwargs to make searching easier... Agreed (though "kwargs" kinda makes my skin crawl). I don't use these features often in my code, but when I do, I follow the convention. The example was just for illustrative purposes, and the names chosen for easy typing. It is important to note that using "args" and "kwargs" is a convention rather than a requirement, analogous to "self". You can use different identifiers, but future maintainers of your code will be annoyed. But it won't affect the operation of the code. I found the test case "test(a=1,b=2,c=3,d=4)" to be most edifying. Regards, -=Dave -- Change is inevitable, progress is not. From mtobis at gmail.com Wed Mar 8 10:47:15 2006 From: mtobis at gmail.com (Michael Tobis) Date: 8 Mar 2006 07:47:15 -0800 Subject: New python.org website In-Reply-To: <1141803728.187013.195770@v46g2000cwv.googlegroups.com> References: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> <1141803728.187013.195770@v46g2000cwv.googlegroups.com> Message-ID: <1141832835.420083.154930@u72g2000cwu.googlegroups.com> > No one > of the complainers and negativists do claim that they could do it much > better. Indeed, I do not have to be able to write a particular program to notice it has bugs. On the other hand, (since I think the design, while not brilliant, is good) fixing the logo is something that can be achieved without too much fuss. > But I think at times it might be usefull to consult > professional aid. In the case of the logo design, I am not sure I agree. I think the twisted logo http://saph.twistedmatrix.com/blog/archives/twisted.png and the PyCon logo http://mirrors.ccs.neu.edu/Python/pub/old-www/pics/pycon-logo.gif were probably not designed by professional designers but rather by people who appreciate Python, and yet do have more appeal to the community and the outside world alike. If we are going to use a snake motif, we should use snakes that look like snakes. I suspect the current shy-tadpoles design was outsourced. (At one point NBC abandoned their very recognizable peacock for a totally vapid geometric design, for which they paid many thousands of dollars. (Including a huge settlement with a Nebraska TV station whose logo they had essentially copied) Eventually they reverted to a somewhat stylized peacock, which was a much better idea.) See http://en.wikipedia.org/wiki/National_Broadcasting_Company_logos It's also interesting in passing to notice that another one of NBC's non-peacock logos was called the "snake", for reasons that will escape anyone who has not seen it animated. In any case, I will probably take a little more time to make the case that the shy tadpoles logo is a mistake. Finally, I disagree that the current logo is better than the neutral but consistently used php logo or the very clever java coffee mug logo, and notably the Ruby on Rails logo, which is first rate. mt From robert.kern at gmail.com Sun Mar 5 19:04:16 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 05 Mar 2006 18:04:16 -0600 Subject: Opening files without closing them In-Reply-To: References: <1141598002.402189.275520@i40g2000cwc.googlegroups.com> Message-ID: Erik Max Francis wrote: > Robert Kern wrote: > >>>I usually use: >>> >>>try: >>> f = open(file) >>> contents = f.read() >>>finally: >>> f.close() >>> >>>But now I am wondering if that is the same thing. Which method would >>>you rather use? Why? >> >>Just keep doing what you are doing, please. > > Note quite. The assignment of the resources to its variable needs to be > done before the try: > > f = open(file) > try: > contents = f.read() > finally: > f.close() Yes, you are correct. -- Robert Kern robert.kern at gmail.com "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 no-spam at no-spam-no-spam.com Fri Mar 10 09:13:07 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Fri, 10 Mar 2006 15:13:07 +0100 Subject: How to best update remote compressed, encrypted archives incrementally? Message-ID: Hello, I want to put (incrementally) changed/new files from a big file tree "directly,compressed and password-only-encrypted" to a remote backup server incrementally via FTP,SFTP or DAV.... At best within a closed algorithm inside Python without extra shell tools. (The method should work with any protocol which allows somehow read, write & seek to a remote file.) On the server and the transmission line there should never be unencrypted data. Usually one would create a big archive, then compress, then encrypt (e.g. with gpg -c file) , then transfer. However for that method you need to have big free temp disk space and most costing: transfer always the complete archive. With proved block-file encryption methods like GPG I don't get the flexibility needed for my task, I guess? ZIP2 format allows encryption (Is this ZIP encryption method supported with Python somehow/basically?). Somehow it would be possible to navigate in a remote ZIP (e.g. over FTP) . But ZIP encryption is also known to be very weak and can be cracked within some hours computing time, at least when every file uses the same password. Another method would be to produce slice files: Create inremental TAR/ZIP archives, encrypt them locally with "gpg -c" and put them as different files. Still a fragile setup, which allows only rough control, needs a common archive time stamp (comparing individual file attributes is not possible), and needs external tools. Very nice would be a method which can directly compare agains and update a single consistent file like ftp://..../archive.zip.gpg Is something like this possible? Robert From xivulon at gmail.com Tue Mar 28 12:01:48 2006 From: xivulon at gmail.com (ago) Date: 28 Mar 2006 09:01:48 -0800 Subject: win32com: error 80004005 In-Reply-To: <1143486605.135183.51180@j33g2000cwa.googlegroups.com> References: <1143486605.135183.51180@j33g2000cwa.googlegroups.com> Message-ID: <1143565308.438786.51880@g10g2000cwb.googlegroups.com> I solved it. If someone else is in the same situation... It was due to a defective installation. I reinstalled python and pywin, re-registered the server and everything worked well. From peter at engcorp.com Wed Mar 29 07:21:41 2006 From: peter at engcorp.com (Peter Hansen) Date: Wed, 29 Mar 2006 07:21:41 -0500 Subject: SEEK_SET defined? In-Reply-To: <1143601887.099994.140430@i40g2000cwc.googlegroups.com> References: <1143601887.099994.140430@i40g2000cwc.googlegroups.com> Message-ID: Roger Miller wrote: > I see that the posixfile module is deprecated. Have the SEEK_SET, etc. > constants moved somewhere else, or do I need to define them myself? In Python 2.5 they have been added to the os module, but for now I think you are probably expected to just continue using posixfile or define them yourself. If you did define them yourself, maybe this would be best, given the current situation: import os try: os.SEEK_SET except AttributeError: os.SEEK_SET, os.SEEK_CUR, os.SEEK_END = range(3) -Peter From lycka at carmen.se Fri Mar 3 09:36:17 2006 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 03 Mar 2006 15:36:17 +0100 Subject: Best python module for Oracle, but portable to other RDBMSes In-Reply-To: <1141335935.848026.102320@u72g2000cwu.googlegroups.com> References: <1140818561.458171.237850@p10g2000cwp.googlegroups.com> <1140826717.186051.261430@i39g2000cwa.googlegroups.com> <1141242710.730153.279490@z34g2000cwc.googlegroups.com> <1141335935.848026.102320@u72g2000cwu.googlegroups.com> Message-ID: dananrg at yahoo.com wrote: > # Print new list > print recordList > > >>>>[872L, 'ACTIVE', , , None, '1.0.0.0', None, None, None] Read the Python library manual chapter 2. Read all of it, it's all very useful information, but take a particular look at str() and repr(). All Python object can be "viewed" in two standard ways, via the str() or repr() functions. In short, the str() stringification is typically to be more end-user friendly, while the repr() stringi- fication is more intended to properly identify exactly what kind of an object we see: what type it is, and often the value too. (Above, you don't see any reasonable value at all in the DbiDate objects, but for some reason that didn't seem to bother you as much as the suffixed L on the long ints.) When you just print a Python object x of some kind, i.e. print x it will be equivalent of print str(x) To see the other representation, use print repr(x) Python collections, such as lists, tuples and dicts, aren't really intended to be printed as is to end users. If recordList is a list, and there is a statement "print recordList", it's probable that it is intended as a diagnostic help to a programmer during development, rather than to an end user. So, it's rather clever to use the repr() stringification, so that it's clear exactly what we see, e.g. all strings are quoted, so you clearly see things as trailing spaces, can differentiate between tabs and sequences of spaces, and aren't confused by commas inside the strings. Also, for longs, you get a trailing L to indicate that this isn't simply a normal integer, but an arbitrarily long one. From steve at REMOVETHIScyber.com.au Sun Mar 12 23:14:40 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 13 Mar 2006 15:14:40 +1100 Subject: Please, I Have A Question before I get started References: <40l912h0aubfgai2en7n465ml9olg746h9@4ax.com> <1hc3qpk.3dr2df1ywhnhnN%aleaxit@yahoo.com> Message-ID: On Sun, 12 Mar 2006 19:43:07 -0800, Alex Martelli wrote: > Steven D'Aprano wrote: > ... >> > Can python do this? I realize I am responsible for the menu sets, >> > pictures .... attaching sounds etc .... >> >> There is no reason why Python can't do this. >> >> If you are new to programming, I suggest you have a look at Pythoncard. > > For the original poster's purposes, I was thinking as PyGame (and PyUI > on top of it) as perhaps more suitable. But, sure, it won't be a > cakewalk, for somebody without any programming experience, with either > toolkit set (Pythoncard+wxPython, or PyUI+PyGame). Where did we go wrong? This sort of project would have been literally a 30 minute job with Apple's now defunct Hypercard program, and 20 of those minutes would be looking for suitable images to use. It's half a decade into the 21st century. Why aren't there modern, advanced GUI development systems that have as simple a front end as technology that existed in 1988? -- Steven. From nospam at nospam.com Thu Mar 2 16:06:53 2006 From: nospam at nospam.com (3c273) Date: Thu, 2 Mar 2006 13:06:53 -0800 Subject: Simple System Tray Icon References: Message-ID: ----quoted---- This is untested, 'cos I'm on a Mac these days, but what you want should look something like: from SysTrayIcon import SysTrayIcon icon = SysTrayIcon('parh/to/icon.ico', "Hover text", {}) How simple do you want? ----/quoted---- I guess I still don't get it. The code you supplied creates an icon and then hangs. from SysTrayIcon import SysTrayIcon icon = SysTrayIcon('PathToMyIcon', "My Application",()) while 1: DoStuff() DoStuff doesn't do happen until I choose 'QUIT' from the icon menu. Any help? I feel like I'm missing something really fundamental here. Thanks again. Louis From sybrenUSE at YOURthirdtower.com.imagination Fri Mar 10 09:49:57 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 10 Mar 2006 15:49:57 +0100 Subject: File Permissions References: <1142000418.480825.247970@v46g2000cwv.googlegroups.com> Message-ID: Sebastjan Trepca enlightened us with: > Those constants are in stat module so add "import stat" before the > program. Yeah, but just opening the file is more Pythonic than first checking if it can be opened in the first place. 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 Tue Mar 28 23:12:59 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 29 Mar 2006 04:12:59 -0000 Subject: sending ctrl C to a process References: <1143598491.283734.37180@t31g2000cwb.googlegroups.com> <1143603413.043217.170540@e56g2000cwe.googlegroups.com> Message-ID: <122k2abgjet672c@corp.supernews.com> On 2006-03-29, s99999999s2003 at yahoo.com wrote: > hi > thanks for the reply. Please properly quote the article to which you're replying so that we can tell who/what your talking to/about. > Actually, i should clarify what i am doing. the program's > output will be displayed to a web browser using cgi, so there > is no keyboard interrupt. The backend cgi script (python > script) will have to send Ctrl-C to break the program. Actually, you don't want to send a Ctrl-C to the program. You want to send a SIGINT signal to the process. That's what the tty line-discipline layer in the tty driver sends to processes attached to a tty when the tty receives the interrupt character (which defaults to Ctrl-C). Sending signals to processes is done using os.kill() http://docs.python.org/lib/os-process.html -- Grant Edwards grante Yow! How do I get HOME? at visi.com From robert.kern at gmail.com Tue Mar 21 11:24:41 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 21 Mar 2006 10:24:41 -0600 Subject: Encoding newlines in XML? In-Reply-To: <17440.4787.24186.25192@montanaro.dyndns.org> References: <17440.4787.24186.25192@montanaro.dyndns.org> Message-ID: skip at pobox.com wrote: > *argh!* I hate XML! There, now that that's off my chest... I think, rather, that you hate XML libraries. Which is perfectly understandable. > I am trying to save Python code as attributes of an XML tag with > xml.dom.minidom machinery. The code, predicatbly enough, contains newlines. > If I do nothing to my program text, upon output I get XML which looks like > this: > > > > When that is later parsed, the newlines are replaced by spaces. That's > clearly no good. > > I verified manually that if I changed the above to > > > > when read in, the entities are replaced by newlines and the function is > restored to its normal indented, multiline self. Other libraries seem to get this right. In [89]: from lxml import etree In [90]: e = etree.Element('SomeTag', text="def _f():\n return 3\n") In [93]: e.attrib Out[93]: {'text': 'def _f():\n return 3\n'} In [94]: etree.dump(e) In [96]: etree.dump(etree.XML('')) I'll bet good money that ElementTree also gets this right. -- Robert Kern robert.kern at gmail.com "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 Mar 9 13:47:32 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 09 Mar 2006 19:47:32 +0100 Subject: implementation of "complex" type In-Reply-To: <1141929197.667102.172060@p10g2000cwp.googlegroups.com> References: <1141895757.128437.159460@i39g2000cwa.googlegroups.com> <1141924817.076466.23680@v46g2000cwv.googlegroups.com> <1141925642.987617.237910@i40g2000cwc.googlegroups.com> <1141929197.667102.172060@p10g2000cwp.googlegroups.com> Message-ID: <47bbi4FerledU1@uni-berlin.de> > Asking sarcastically why I am "reinventing the wheel" is a funny way of > being friendly. I said absolutely nothing to indicate that I had > re-implemented my own version of complex. And, by the way, even if I > had, so what? Why is it even worth commenting on? Well - obviously its not worth commenting on your posts. Diez From prettyboy988-google at yahoo.com Fri Mar 3 03:20:21 2006 From: prettyboy988-google at yahoo.com (P Boy) Date: 3 Mar 2006 00:20:21 -0800 Subject: string stripping issues In-Reply-To: <1141337944.536321.95970@p10g2000cwp.googlegroups.com> References: <1141335954.481084.277030@p10g2000cwp.googlegroups.com> <1141337436.603446.58980@p10g2000cwp.googlegroups.com> <1141337944.536321.95970@p10g2000cwp.googlegroups.com> Message-ID: <1141374021.304714.238910@i39g2000cwa.googlegroups.com> This seems like a web page parsing question. Another approach can be as follows if you know the limiting token strings: a.split(' ')[1].split('\r\n')[0] From tjreedy at udel.edu Tue Mar 7 12:47:29 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 7 Mar 2006 12:47:29 -0500 Subject: Peter Naur wins ACM Turing Award References: <1141713321.760459.66010@j33g2000cwa.googlegroups.com> <18fPf.157$xM2.46142@news20.bellglobal.com> Message-ID: "Colin J. Williams" wrote in message news:18fPf.157$xM2.46142 at news20.bellglobal.com... >> Terry Reedy wrote: >> >>>http://campus.acm.org/public/pressroom/press_releases/3_2006/turing_3_01_2006.cfm >>> >>>Peter Naur was co-developer of Backus/Naur grammar notation, co-author >>>and >>>editor of the Algol 60 specification, and co-developer of a successful >>>Algol compiler. > Peter Naur's honour is long overdue. That was my reaction also, tempered by three observations. 1. I do not have enough detailed knowledge of who invented what when to judge details of credit allocation. 2. The importance of Algol60 (and the impetus of the award) is not its usage in the 60s but the dominance of the family of languages it inspired, including, at least in some important parts, Python. But this has been a gradual development. So when did the award become 'due', to make it 'overdue' now? (I would say by 1990, at least.) 3. To call it overdue suggests that it should have been awarded before, *instead of* to someone else. But I am not about to suggest which of the previous (worthy, I am sure) recipients he should have been instead of ;-). Nobel's will specificed awards for the most important contribution in the previous year. The Nobel committees recognized that this is ludicrous in that recognition of importance can take decades. Terry Jan Reedy From fulvio at pc.jaring.my Thu Mar 23 08:10:18 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Thu, 23 Mar 2006 21:10:18 +0800 Subject: Some info In-Reply-To: References: <1142610889.512781.69650@j33g2000cwa.googlegroups.com> Message-ID: <200603232110.19092.fulvio@pc.jaring.my> Alle 22:14, mercoled? 22 marzo 2006, Sybren Stuvel ha scritto: > different partitions might have, though. Then again, it all depends on > the filesystems in use. Then I should make some extra programming to catch these info, according to which OS will run it :-( Regarding the names, CDROMs DVD have a label, which might be written during the burning process. Also partition have name, which can be written by fdisk, or in MS windows properties. Just a comparison : Imaging something like WhereIsIt (Windows) Gwhere (Linux), but in my opinion I'd like to give it free and less weak (as the before-mentioned programs). F From deets at nospam.web.de Wed Mar 8 15:41:58 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 08 Mar 2006 21:41:58 +0100 Subject: a question about zip... In-Reply-To: <1141849339.040283.213510@j33g2000cwa.googlegroups.com> References: <1141849339.040283.213510@j33g2000cwa.googlegroups.com> Message-ID: <478tsoFdlnq5U1@uni-berlin.de> KraftDiner schrieb: > I had a structure that looked like this > ((0,1), (2, 3), (4, 5), (6,7) > > I changed my code slightly and now I do this: > odd = (1,3,5,7) > even = (0,2,4,6) > all = zip(even, odd) > > however the zip produces: > [(0, 1), (2, 3), (4, 5), (6, 7)] > > Which is a list of tuples.. I wanted a tuple of tuples... Use tuple(zip(...)) There is a reason that zip returns a list: appending to a list is considered a "natural" operation, whereas extending an immutable(!) tuple creates a _new_ tuple for each entry. Which is a comparable costly operation - actually quadratic complexity instead of linear. So - if you need a tuple afterwards, convert it as shown above. Diez From cito at online.de Tue Mar 21 11:24:33 2006 From: cito at online.de (Christoph Zwerschke) Date: Tue, 21 Mar 2006 17:24:33 +0100 Subject: ** Operator In-Reply-To: References: <1142833145.976550.104830@v46g2000cwv.googlegroups.com> <1142833540.860154.137040@u72g2000cwu.googlegroups.com> <1hcgw5p.1ufznwe1lxeagfN%aleaxit@yahoo.com> <1142864492.645457.291240@j33g2000cwa.googlegroups.com> <441ed65c$1_3@newspeer2.tds.net> Message-ID: Christoph Zwerschke wrote: > Christoph Zwerschke wrote: >> Kent Johnson wrote: >>> The way to make this change happen is to submit a bug report with >>> your suggested change. See the link at the bottom of the above page >>> to find out how. >> >> I know, but I wanted to see at least one person assenting before doing >> so. Anyway, I took your words as assent and filed a bug report now ;-) > > ... which was promptly rejected. ... but now it has been checked in by somebody else anyway. The Python gods sometimes move in mysterious ways ;-) -- Christoph From johnjsal at NOSPAMgmail.com Fri Mar 24 19:58:11 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 24 Mar 2006 19:58:11 -0500 Subject: a problem to solve In-Reply-To: <1143237220.103038.52200@t31g2000cwb.googlegroups.com> References: <5oiUf.1818$No6.41433@news.tufts.edu> <1143237220.103038.52200@t31g2000cwb.googlegroups.com> Message-ID: mensanator at aol.com wrote: > a = [0xf5fdc,0xf6edb,0xbddb7,0x6fddd,0xeb7ed,0xb977f,0xbfed3,0xedef5] > b = [0xddb7d,0xfaddb,0xde75f,0xeef7a,0xdd77b,0xdfbce,0xb77dd,0x7ef5d] > c = [0xf37bd,0xdfaee,0xddd6f,0xddfb6,0xb9efb,0xb7bbe,0xecfbd,0xb75df] > d = [0x77edb,0xbb7ee,0xdf773,0x7bdeb,0x7ddaf,0xdeeeb,0xfb35f,0xbb7dd] > Once you see that a[0],b[0],c[0],d[0] is not a solution, try a > different set of switches. Repeat until you find a set that works. > There is, in fact a solution, but I won't reveal it unless you ask. Using your hex list, I combined the four correct switches with the & operator, and the result was 0. Shouldn't it be 1 for the correct answer? From cito at online.de Sat Mar 25 05:56:16 2006 From: cito at online.de (Christoph Zwerschke) Date: Sat, 25 Mar 2006 11:56:16 +0100 Subject: Multiplying sequences with floats In-Reply-To: <1143239583.002604.44010@v46g2000cwv.googlegroups.com> References: <1143239583.002604.44010@v46g2000cwv.googlegroups.com> Message-ID: Caleb Hattingh wrote: > 4.0//2 doesn't return an integer, but the equality against an integer > still holds. I agree that integer division should return an integer, > because using the operator at all means you expect one. There are actually two conflicting expectations here: You're right, the semantics of a floor operation let you expect an int, but on the other hand, the result type of all other binary operations is the common type into which the operands are casted before the operation, and the result type of math.floor() is always float, even for an int operand. The thing that I thought is a bit awkward is that a//b * some_list will not work if a or b is a float, even if it represents an integer and even though the result of a//b always represents an integer. Now there are two ways to resolve this: a) a//b always returns an int (or long) b) n * some_list works if n is a float representing an integer I was actually considering solution b), not a). By the way, solution a) has another drawback: What would you return if a=1e200 and b=1, or a=1 and b=1e-200? Of course, a floor division would be pretty silly with such numbers, but returning a long number with 200 digits of which most are wrong anyway somehow does not look like the right thing to do. -- Christoph From andrearo at stud.ntnu.no Fri Mar 24 15:33:55 2006 From: andrearo at stud.ntnu.no (=?ISO-8859-1?Q?Andreas_R=F8sdal?=) Date: Fri, 24 Mar 2006 21:33:55 +0100 Subject: Performance profiling Python code Message-ID: Hi, I'm using the Python profiler to optimize a pathfinding algorithm of a game, and would like some help from someone who knows how to improve the performance of Python code. The algorithm is A-Star, and it works correctly. However, the interface that I made between the A-Star pathfinding algorithm and the map data structure is what I've found to be a bottle-neck so far. As a start, I'd like to optimize the methods with the highest cumulative time spent using CPU, which are the ones on the top of the profiling out-put attached below (get_tile_adjacent etc.) So are you able to spot any solutions to improving the performance of the methods which I've indentified as bottlenecks here? Thanks in advance! Andreas R. The source code of the main faile is here: http://svn.gna.org/viewcvs/openrts/trunk/openrts/common/map.py?rev=89&view=markup Profiling output is here: ncalls tottime percall cumtime percall filename:lineno(function) /home/andreas/openrts/openrts/openrts/common/map.py:190(get_tile_adjacent) 162002 0.680 0.000 0.680 0.000 /home/andreas/openrts/openrts/openrts/common/map.py:56(get_tile) 129600 0.570 0.000 0.570 0.000 /home/andreas/openrts/openrts/openrts/common/map.py:217(wrap_map_pos) 129837 0.480 0.000 0.480 0.000 :0(append) 8100 0.190 0.000 0.430 0.000 /home/andreas/openrts/openrts/openrts/common/map.py:253(get_tile_height_pos) 8100 0.080 0.000 0.270 0.000 /usr/lib/python2.4/random.py:213(randint) 8100 0.160 0.000 0.190 0.000 /usr/lib/python2.4/random.py:149(randrange) 1 0.000 0.000 0.170 0.170 /home/andreas/openrts/openrts/openrts/common/map.py:26(__init__) 1 0.070 0.070 0.170 0.170 /home/andreas/openrts/openrts/openrts/common/map.py:32(init_map) 8100 0.080 0.000 0.110 0.000 /home/andreas/openrts/openrts/openrts/common/map.py:234(get_tile_height) From y.glodt at sitasoftware.lu Fri Mar 3 06:26:14 2006 From: y.glodt at sitasoftware.lu (Yves Glodt) Date: Fri, 03 Mar 2006 12:26:14 +0100 Subject: encoding problem Message-ID: <440827D6.3060501@sitasoftware.lu> Hi list, Playing with the great pysvn I get this problem: Traceback (most recent call last): File "D:\avn\mail.py", line 80, in ? mailbody += diff UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 10710: ordinal not in range(128) It seems the pysvn.client.diff function returns "bytes" (as I read in the changelog of pysvn: http://svn.haxx.se/dev/archive-2005-10/0466.shtml) How can I convert this string so that I can contatenate it to my "regular" string? Best regards, Yves From roy at panix.com Wed Mar 8 14:50:03 2006 From: roy at panix.com (Roy Smith) Date: Wed, 8 Mar 2006 19:50:03 +0000 (UTC) Subject: why no block comments in Python? References: <_MCPf.1749$No6.40293@news.tufts.edu> <1141843360.140692.44180@i39g2000cwa.googlegroups.com> Message-ID: Warby wrote: >Eliminating block comments eliminates uncertainty. :) An even better way to eliminate uncertainty is to eliminate the code. Commenting out is fine for a quick test during development. Once the code is committed, the dead code should be eliminated completely. From alainpoint at yahoo.fr Mon Mar 13 15:41:07 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 13 Mar 2006 12:41:07 -0800 Subject: Is this possible in Python? In-Reply-To: References: <1142238871.199749.243470@p10g2000cwp.googlegroups.com> Message-ID: <1142282467.270698.142780@p10g2000cwp.googlegroups.com> Hello again, I am disappointed. You are the experts, you've got to try harder ;-) What i want is a generalisation of this tiny function: import tokenize import token def magic_function(s): readline = open(s.gi_frame.f_code.co_filename).readline for t in tokenize.generate_tokens(open(s.gi_frame.f_code.co_filename).readline): t_type,t_string,(r_start,c_start),(r_end,c_end),line = t if r_start == s.gi_frame.f_code.co_firstlineno: if t_string=="magic_function": args= line.split(t_string) arg=args[1] return arg # returns its own argument ! print magic_function(i+2 for i in [1,2]) There ought to be a way to make it work for more than generator expressions !!! From fredrik at pythonware.com Fri Mar 31 03:41:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 31 Mar 2006 10:41:58 +0200 Subject: Best IDE for Python? References: <1143783179.361616.76750@i39g2000cwa.googlegroups.com> <442ce5fa$0$6691$626a54ce@news.free.fr> Message-ID: bruno wrote: > Nonsense ! *Ed* is the the standard editor ! > > http://www.gnu.org/fun/jokes/ed.msg.html unless you're on Windows, where edlin is the true standard editor. as you can see, Microsoft's usability team has made some massive improvements (note how well it deals with the "eat flaming death" command): C:\> edlin Filename missing. C:\> edlin spam New file. *help Syntax error. *quit Do you want to abort (Yes=Y, No=N)? n Syntax error. *exit C:\>edlin spam End of input file. *hello? Syntax error. *eat flaming death C:\>edlin foo End of input file. *^C *^C *^D Syntax error. *^Z Syntax error. *^C *^C From raNOsky at deveSPAMler.com Mon Mar 13 13:41:38 2006 From: raNOsky at deveSPAMler.com (Giovanni Bajo) Date: Mon, 13 Mar 2006 19:41:38 +0100 Subject: trying to find repeated substrings with regular expression References: <1142272818.513560.198880@e56g2000cwe.googlegroups.com> Message-ID: Robert Dodier wrote: > Hello all, > > I'm trying to find substrings that look like 'FOO blah blah blah' > in a string. For example give 'blah FOO blah1a blah1b FOO blah2 > FOO blah3a blah3b blah3b' I want to get three substrings, > 'FOO blah1a blah1b', 'FOO blah2', and 'FOO blah3a blah3b blah3b'. > [...] > Can someone suggest a regular expression which will return > groups corresponding to the FOO substrings above? FOO.*?(?=(?:FOO|$)) -- Giovanni Bajo From robert.kern at gmail.com Sun Mar 5 14:16:39 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 05 Mar 2006 13:16:39 -0600 Subject: Python advocacy in scientific computation In-Reply-To: <1141583453.403143.189400@i40g2000cwc.googlegroups.com> References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> <1141583453.403143.189400@i40g2000cwc.googlegroups.com> Message-ID: sturlamolden wrote: > Robert Kern wrote: >>Yes, and this is why you will keep saying, "My simulation is running too >>slowly," and "My simulation is running out of memory." All the vectorization you >>do won't make a quadratic algorithm run in O(n log(n)) time. Knowing the right >>algorithm and the right data structures to use will save you programming time >>and execution time. Time is money, remember, and every hour you spend tweaking >>Matlab code to get an extra 5% of speed is just so much grant money down the drain. > > Yes, and that is why I use C (that is ISO C99, not ANSI C98) instead of > Matlab for everything except trivial tasks. The design of Matlab's > language is fundamentally flawed. I once wrote a tutorial on how to > implement things like lists and trees in Matlab (using functional > programming, e.g. using functions to represent list nodes), but it's > just a toy. And as Matlab's run-time does reference counting insted of > proper garbage collection, any datastructure more complex than arrays > are sure to leak memory (I believe Python also suffered from this as > some point). Python still uses reference counting and has several very good data structures more complex than arrays. And yet, most programs don't leak memory. > Matlab is not useful for anything except plotting data > quickly. And as for the expensive license, I am not sure its worth it. > I have been considering a move to Scilab for some time, but it too > carries the burden of working with a flawed language. And you need to ask why Python is a better Matlab than Matlab? -- Robert Kern robert.kern at gmail.com "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 http Sun Mar 19 16:37:05 2006 From: http (Paul Rubin) Date: 19 Mar 2006 13:37:05 -0800 Subject: cmp() on integers - is there guarantee of returning only +-1 or 0? References: <441dd94c$0$20108$834e42db@reader.greatnowhere.com> Message-ID: <7xslpep14u.fsf@ruckus.brouhaha.com> "Dmitry Anikin" writes: > doc says that it must be > 0, or < 0, but it seems that > it returns +1 or -1. Can it be reliably used to get the sign of x: > cmp(x, 0) like pascal Sign() function does? The doc says (http://docs.python.org/lib/built-in-funcs.html): cmp(x,y) Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y. > I mean, I'm pretty sure that it can be used, but is it mentioned > somewhere in language spec, or it may be implementation defined? The doc doesn't specify that it returns -1/0/+1 so by definition it's implementation defined. > If so, any other simple means of _reliably_ getting the sign? Ehh, every way I see offhand is at least a little bit messy. From omouse at gmail.com Wed Mar 15 11:52:29 2006 From: omouse at gmail.com (OMouse) Date: 15 Mar 2006 08:52:29 -0800 Subject: how to get 20000 html pages content quickly from one server? In-Reply-To: <1142439755.840346.181060@p10g2000cwp.googlegroups.com> References: <1142439755.840346.181060@p10g2000cwp.googlegroups.com> Message-ID: <1142440417.739060.251670@j52g2000cwj.googlegroups.com> JuHui wrote: > Hi > I want to get 200000 html pages content from one server, you know > urllib.urlopen need construct network connection, it will be very > slowly, how to speed up this function? > I try to using multi-thread, it speed up, but I want to quickly more, > any idea about it? > Thanks! Why don't you try and use wget? From kbk at shore.net Fri Mar 17 00:36:20 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 17 Mar 2006 00:36:20 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200603170536.k2H5aK9n007030@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 392 open ( +6) / 3094 closed ( +5) / 3486 total (+11) Bugs : 907 open (+18) / 5646 closed (+10) / 6553 total (+28) RFE : 213 open ( +1) / 202 closed ( +1) / 415 total ( +2) New / Reopened Patches ______________________ new exit and quit objects (2006-03-09) CLOSED http://python.org/sf/1446372 opened by Georg Brandl zipfile: support for ZIP64 (2006-03-09) http://python.org/sf/1446489 opened by Ronald Oussoren patch for 1441408 compiler fails to spot extended slice (2006-03-09) http://python.org/sf/1446847 opened by Grant Olson Patch for bug 1441486: bad unary minus folding in compiler (2006-03-09) http://python.org/sf/1446922 opened by Grant Olson logging: findCaller() sometimes raises AttributeError (2006-03-10) CLOSED http://python.org/sf/1447410 opened by Kevin J Bluck ConnectRegistry blocks all threads (2006-03-12) http://python.org/sf/1448199 opened by Lars L decorator module (2006-03-12) http://python.org/sf/1448297 opened by Georg Brandl declspec for ssize_t (2006-03-12) http://python.org/sf/1448484 opened by Zooko O'Whielacronx const PyDict_Type ? (2006-03-12) http://python.org/sf/1448488 opened by Zooko O'Whielacronx email.message.py charset can be unicode instance (2006-03-13) http://python.org/sf/1449244 opened by Tokio Kikuchi Splitting CJK codecs from pythoncore dll (2006-03-14) http://python.org/sf/1449471 opened by Hye-Shik Chang Patches Closed ______________ new exit and quit objects (2006-03-09) http://python.org/sf/1446372 closed by gbrandl logging: findCaller() sometimes raises AttributeError (2006-03-10) http://python.org/sf/1447410 closed by vsajip Several minor fixes for NULL checks, etc. (2006-03-06) http://python.org/sf/1444030 closed by nnorwitz New with semantics (2006-03-08) http://python.org/sf/1445739 closed by nnorwitz Python memory allocator: Free memory (2005-02-15) http://python.org/sf/1123430 closed by tim_one New / Reopened Bugs ___________________ extended slice behavior inconsistent with docs (2006-03-09) http://python.org/sf/1446619 opened by Steven Bethard bug with xmlrpclib (2006-03-09) http://python.org/sf/1446690 opened by varun bhansaly whatsnew 2.5: pep 353, python -m (2006-03-09) http://python.org/sf/1447031 opened by Gene Tani tkinter Dialog fails when more than four buttons are used (2006-03-10) http://python.org/sf/1447222 opened by Hernan P. Dacharry tkinter Dialog fails when more than four buttons are used (2006-03-10) CLOSED http://python.org/sf/1447234 opened by Hernan P. Dacharry Mac Framework build fails on intel (2006-03-10) http://python.org/sf/1447587 opened by Michael Mondragon make frameworkinstall fails on Intel Macs (2006-03-10) http://python.org/sf/1447607 opened by Michael Mondragon "reindent.py" exposes bug in tokenize (2006-03-10) CLOSED http://python.org/sf/1447633 opened by Edward C. Jones traceback.format_exception_only() and SyntaxError (2006-03-11) http://python.org/sf/1447885 opened by Remy Blank Unable to stringify datetime with tzinfo (2006-03-11) http://python.org/sf/1447945 opened by Ilpo Nyyss?nen Defining a class with __dict__ brakes attributes assignment (2006-03-11) http://python.org/sf/1448042 opened by Michal Kwiatkowski problems with too many sockets in FreeBSD (2006-03-12) http://python.org/sf/1448058 opened by aix-d gettext.py breaks on plural-forms header (2006-03-12) http://python.org/sf/1448060 opened by Danilo Segan re search infinite loop (2006-03-12) http://python.org/sf/1448325 opened by Don Allen Convertion error for latin1 characters with iso-2022-jp-2 (2006-03-12) CLOSED http://python.org/sf/1448490 opened by Francois Duranleau asyncore dispatcher.__getattr__() masks self._map (2006-03-12) http://python.org/sf/1448639 opened by Doug White datetime.__init__ cannot be overridden (2006-03-13) CLOSED http://python.org/sf/1448640 opened by Martin Blais Subscript operations generating incorrect code (2006-03-13) CLOSED http://python.org/sf/1448804 opened by Nick Coghlan urllib2+https+proxy not working (2006-03-13) http://python.org/sf/1448934 opened by Rui Martins urllib2+https+proxy not working (2006-03-14) CLOSED http://python.org/sf/1449397 opened by Rui Martins optparse: extending actions missing ALWAYS_TYPES_ACTIONS (2006-03-13) http://python.org/sf/1449311 opened by Christopher Build of readline fails (2006-03-14) CLOSED http://python.org/sf/1450019 opened by Sydney Weidman int() and isdigit() accept non-digit numbers when using unic (2006-03-15) CLOSED http://python.org/sf/1450212 opened by Pierre-Fr?d?ric Caillaud windows python truncates files when reading them (2006-03-15) CLOSED http://python.org/sf/1450456 opened by tom berger Python build fails for gcc 4.x from Gnu (2006-03-15) http://python.org/sf/1450807 opened by John W. Grove msgfmt.py: fuzzy messages not correctly found (2006-03-16) http://python.org/sf/1451341 opened by Hanno Schlichting reading very large files (2006-03-16) http://python.org/sf/1451466 opened by christen os.startfile() still doesn't work with Unicode filenames (2006-03-16) http://python.org/sf/1451503 opened by roee88 segfault in optimize_code() (2006-03-16) CLOSED http://python.org/sf/1451641 opened by Kristj?n Valur OS/X on i386 framework build (2006-03-17) http://python.org/sf/1451717 opened by Ian Holsman Bugs Closed ___________ handling comments with markupbase and HTMLParser (2006-03-04) http://python.org/sf/1442874 closed by gbrandl tkinter Dialog fails when more than four buttons are used (2006-03-10) http://python.org/sf/1447234 closed by gbrandl "reindent.py" exposes bug in tokenize (2006-03-10) http://python.org/sf/1447633 closed by goodger PCbuild/readme.txt description not quite right (2005-04-15) http://python.org/sf/1183896 closed by gbrandl Convertion error for latin1 characters with iso-2022-jp-2 (2006-03-13) http://python.org/sf/1448490 closed by perky datetime.__init__ cannot be overridden (2006-03-13) http://python.org/sf/1448640 closed by mwh Subscript operations generating incorrect code (2006-03-13) http://python.org/sf/1448804 closed by ncoghlan urllib2+https+proxy not working (2006-03-14) http://python.org/sf/1449397 deleted by ruibmartins Build of readline fails (2006-03-14) http://python.org/sf/1450019 closed by nnorwitz int() and isdigit() accept non-digit unicode numbers (2006-03-15) http://python.org/sf/1450212 closed by lemburg windows python truncates files when reading them (2006-03-15) http://python.org/sf/1450456 deleted by object segfault in optimize_code() (2006-03-16) http://python.org/sf/1451641 closed by rhettinger New / Reopened RFE __________________ Python should use 3GB Address Space on Windows (2006-03-14) http://python.org/sf/1449496 opened by Martin Gfeller bisect should support a custom comparison function (2006-03-16) http://python.org/sf/1451588 opened by Jonathan S. Joseph RFE Closed __________ friendly quit object (2006-01-13) http://python.org/sf/1404859 closed by gbrandl From webraviteja at gmail.com Wed Mar 8 17:25:36 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 8 Mar 2006 14:25:36 -0800 Subject: RAD tutorials and tools for GUI development with Python? In-Reply-To: References: <16de708d0603080251t3f62958btea3e13535bc4312c@mail.gmail.com> Message-ID: <1141856736.761780.117340@j33g2000cwa.googlegroups.com> Jarek Zgoda wrote: > Michael Ekstrand napisa?(a): > > > Glade + PyGTK + libglade does the trick. libglade (exposed as gtk.glade > > in Python) allows you to load Glade interface files (the raw XML Glade > > saves your interfaces as) and then connect to various signals, access > > the widgets, etc. > > > > About as fast as anything I've found. Much slicker than VB (the only > > previous RAD experience I'd had that I could actually do anythin in). > > GTK on Windows looks worse than wx, but is easier to program. Anyway, it > is not as easy as, say, Delphi. Indeed. The OP already indicates that he has experience with Delphi and is trying to apply to a domain that Delphi dominated (to those who knew it anyway) over a decade. The best solution then is not to do pure Python solution but to bring it in to supplement Delphi in areas that Delphi is not so good at. Python for Delphi is excellent. http://mmm-experts.com/Products.aspx?ProductId=3 From invalidemail at aerojockey.com Sat Mar 11 19:34:38 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 11 Mar 2006 16:34:38 -0800 Subject: Help Create Good Data Model References: <1142107183.358685.266440@i39g2000cwa.googlegroups.com> Message-ID: <1142123678.381251.75280@z34g2000cwc.googlegroups.com> mwt wrote: > def get_data(self, key): > """Returns a COPY of data element.""" > try: > self.mutex.acquire() > return copy.deepcopy(self.data[key]) > finally: > self.mutex.release() self.mutex.acquire() should be outside the try block, like this: self.mutex.acquire() try: return copy.deepcopy(self.data[key]) finally: self.mutex.release() The reason is: what if the call to self.mutex.acquire fails (raises an exception)? Suppose that another thread (#1) has the mutex, and this thread (#2) is waiting on it, when an exception is raised in it (say a timeout, keyboard interrupt, or runtime error). What will happen? Because the acquire call is inside the try block, the finally block gets run, and thread #2 releases the mutex being held by #1. But wait! Now let's say there's a third thread (#3) that's also waiting on this mutex. When #2 releases the mutex, #3 runs. But #1 is not done... #3 corrupts the data. You've just destroyed the secret plans. You're fired. The same logic applies to open/close, allocate/deallocate, set/unset, or any other resource acquisistion. Acquire the resource before the try block, release it in the finally block. (Note: it may be the case that 1. the acquisition function cannot raise an exception for some reason, or 2. attempting to release a unacquired resource is harmless, in which case it won't exactly hurt to put the acquisition inside the try block. It might be true of mutexes for all I know. But even in those rare cases, I recommend always sticking to the idiom for consistency.) Carl Banks From steve at REMOVETHIScyber.com.au Sun Mar 5 08:36:14 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 06 Mar 2006 00:36:14 +1100 Subject: Argument Precedence (possible bug?) References: <1141562380.331820.42260@i40g2000cwc.googlegroups.com> <1141562704.979483.63730@i40g2000cwc.googlegroups.com> Message-ID: On Sun, 05 Mar 2006 04:45:05 -0800, vbgunz wrote: > Hello all, > > I am just learning Python and have come across something I feel might > be a bug. Please enlightenment me... The following code presents a > challenge. How in the world do you provide an argument for *arg4? > > ## ============================================================ > def argPrecedence(par1, par2=0, par3=0, *par4, **par5): > print 'par1 =', par1, ' # positional argument' > print 'par2 =', par2, ' # keyword argument' > print 'par3 =', par3, ' # keyword argument' > print 'par4 =', par4, ' # argument converted to tuple' > print 'par5 =', par5, ' # argument converted to dictionary' No, you are confused about * and ** arguments. They don't convert arguments, they collect them. def f(a, b=0, *args, **kwargs): print "a =", a print "b =", b print "args =", args print "kwargs =", kwargs Now call the function different ways, and see which will work and which won't. f(1) f(1, 2) f(1, b=2) f(a=1, b=2) f(b=2, a=1) Notice that this does not work: f(b=3) Do you understand why not? Now look at these calls: f(1, 2, 3) f(1, 2, 3, 4, 5, 6) f(1, 2, 3, 4, 5, 6, foo=7, bar=8) In the function definition f(a, b=0, *args, **kwargs), a must be supplied, b has a default value so it can be left out. Both a and b can be provided as positional arguments like f(2, 3) or as keyword arguments. Any _extra_ positional arguments are collected into a tuple called args, and any _extra_ keyword arguments are collected into a dictionary called kwargs. Of course you can use any names you like. Hope this helps, -- Steven. From no-spam at no-spam-no-spam.com Fri Mar 10 08:15:50 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Fri, 10 Mar 2006 14:15:50 +0100 Subject: how to validate a proxy is alive? In-Reply-To: <1141995025.458112.103900@e56g2000cwe.googlegroups.com> References: <1141994373.525265.165060@i39g2000cwa.googlegroups.com> <1141995025.458112.103900@e56g2000cwe.googlegroups.com> Message-ID: JuHui wrote: > I want to get a html page content via a http proxy. > befor this, I want to check the proxy. how to validate it? > thanks > most simple by a socket-connect / error if non-existing: >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> s.connect(('nonexisting-proxy-server',3129)) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in connect error: (10061, 'Connection refused') >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> s.connect(('existing-proxy-server',3128)) >>> 1 1 >>> Robert From TheExpert at ExpertHumor.com Thu Mar 30 23:26:08 2006 From: TheExpert at ExpertHumor.com (Expert Humor) Date: 31 Mar 2006 04:26:08 GMT Subject: Will illegal immigrants get deported?.........Of course not..................... Message-ID: <733040933006@free.teranews.com> Our politicians just wanted to blow us some sunshine. Get the details from The Expert: http://www.ExpertHumor.com/ *** Free account sponsored by SecureIX.com *** *** Encrypt your Internet usage with a free VPN account from http://www.SecureIX.com *** From xah at xahlee.org Thu Mar 16 20:03:28 2006 From: xah at xahlee.org (Xah Lee) Date: 16 Mar 2006 17:03:28 -0800 Subject: Xah's Edu Corner: The Concepts and Confusions of Pre-fix, In-fix, Post-fix and Fully Functional Notations In-Reply-To: <1142490052.127055.50130@v46g2000cwv.googlegroups.com> References: <1142490052.127055.50130@v46g2000cwv.googlegroups.com> Message-ID: <1142557408.309956.132120@e56g2000cwe.googlegroups.com> Xah Lee wrote: ? The Concepts and Confusions of Pre-fix, In-fix, Post-fix and Fully Functional Notations http://xahlee.org/UnixResource_dir/writ/notations.html ? A side note: the terminology ?Algebraic? Notation is a misnomer. It seems to imply that such notations have something to do with the branch of math called algebra while other notation systems do not. The reason the name Algebraic Notation is used because when the science of algebra was young, around 1700s mathematicians are dealing with equations using symbols like ?+ ? =? written out similar to the way we use them today. This is before the activities of systimatic investigation into notation systems as necessitated in the studies of logic in 1800s or computer languages in 1900s. So, when notation systems are actually invented, the conventional way of infixing ?+ ? =? became known as algebraic because that's what people think of when seeing them. Xah xah at xahlee.org ? http://xahlee.org/ From webraviteja at gmail.com Tue Mar 14 22:50:13 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 14 Mar 2006 19:50:13 -0800 Subject: Please, I Have A Question before I get started In-Reply-To: <4415b830$1_1@newspeer2.tds.net> References: <40l912h0aubfgai2en7n465ml9olg746h9@4ax.com> <1hc3qpk.3dr2df1ywhnhnN%aleaxit@yahoo.com> <1142223546.729924.323410@v46g2000cwv.googlegroups.com> <1142232683.680734.163550@z34g2000cwc.googlegroups.com> <4415b830$1_1@newspeer2.tds.net> Message-ID: <1142394613.741386.158740@j33g2000cwa.googlegroups.com> I did not check prices earlier. There are many other clones. How about Hyperstudio? $70 for student edition? From felipe.lessa at gmail.com Mon Mar 20 10:55:00 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Mon, 20 Mar 2006 12:55:00 -0300 Subject: what's the general way of separating classes? In-Reply-To: References: Message-ID: <1142870100.4558.2.camel@kenshin> Em Seg, 2006-03-20 ?s 15:42 +0000, John Salerno escreveu: > Are related classes put into a single module then? Or is there some > recommended method for how to handle this? IMHO, if they can be put on the same file without creating a huge one (3000+ lines), then do it. If you can't, then instead of creating a huge: program/module.py You can do lots of program/modules/*.py And create an program/modules/__init__.py that have something like from program.modules.class1 import class1 from program.modules.class2 import class2 And, in the rest of your program, you can import class1 and class2 by just issuing from program.modules import class1, class2 HTH, -- Felipe. From deets at nospam.web.de Fri Mar 24 03:30:09 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 24 Mar 2006 09:30:09 +0100 Subject: Bitwise OR? In-Reply-To: <1143187977.384459.225840@i40g2000cwc.googlegroups.com> References: <1143187977.384459.225840@i40g2000cwc.googlegroups.com> Message-ID: <48hp0hFipp0jU1@uni-berlin.de> xkenneth schrieb: > Why is 3500 | -67 equal to 3500 instead of -3567? It isn't - its -67. Diez From finite.automaton at gmail.com Mon Mar 20 12:24:14 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 20 Mar 2006 09:24:14 -0800 Subject: user-supplied locals dict for function execution? Message-ID: <1142875454.906993.126370@v46g2000cwv.googlegroups.com> Can anyone think of a way to substitute a user-supplied dictionary as the local dict for a function call? e.g. def f(): x = 5 d = {} exec_function_in_dictionary( f, d ) # ??? print d["x"] # 5 #-------------- Right now, the way I'm doing this is to parse the function body out of its source code and call exec on the body. This has problems --- notably that it only works on functions for which source code can be found, also that the parsing is tricky (but I can fix that). From brochu121 at gmail.com Wed Mar 15 16:09:00 2006 From: brochu121 at gmail.com (david brochu jr) Date: Wed, 15 Mar 2006 16:09:00 -0500 Subject: Clearing IE history Message-ID: <9583ed900603151309w60bd2625k7febe13b772dc9c8@mail.gmail.com> Hello I am trying to automate the clearing of IE history using python but keep running into problems. I cannot seem to find a good resource online about this, and I can't find an object in InternetExplorer's object module to point me in the right direction. I would rather not have to deal with deleting a bunch of registry values and keys or paths to do this, as this script will be run on numerous machines. Anyone have any ideas? -------------- next part -------------- An HTML attachment was scrubbed... URL: From oliphant.travis at ieee.org Wed Mar 15 07:07:08 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Wed, 15 Mar 2006 05:07:08 -0700 Subject: installing numpy In-Reply-To: <1142416764.080637.202340@e56g2000cwe.googlegroups.com> References: <1142416764.080637.202340@e56g2000cwe.googlegroups.com> Message-ID: cesco wrote: > Hi, > > I'm trying to install the numpy library (precisely > numpy-0.9.6-py2.4-linux-i686) on Linux but I encounter several This is a dumb pre-built binary package (useful perhaps because it links against ATLAS already) built using distutils. You don't build it and install it using setup.py you just un-tar it in the / directory and start using it. You only run python setup.py install when you have a source file. You can download the sources if you want and build it yourself using: python setup.py install > Finally I tried to move the folder numpy to the location where all the > third-party modules are installed, that in my case is > /usr/lib/python2.4/site-packages/ and run the command from there like: > python numpy/setup.py install Presumably, you can copy the files directly there and then start using it (don't run setup.py though, there is no need). After copying the files over to your site-packages directory, just start python and do import numpy -Travis From codecraig at gmail.com Thu Mar 30 09:18:37 2006 From: codecraig at gmail.com (abcd) Date: 30 Mar 2006 06:18:37 -0800 Subject: How to determine an object is "scriptable" References: <1143726903.153135.317880@j33g2000cwa.googlegroups.com> Message-ID: <1143728317.535829.121950@i39g2000cwa.googlegroups.com> Richard Brodie wrote: > subscriptable: supports an indexing operator, like a list does. doesn't seem to be a builtin function or module...or is that just your definition of subscriptable? From mahs at telcopartners.com Sun Mar 19 22:15:50 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Sun, 19 Mar 2006 19:15:50 -0800 Subject: String comparison question In-Reply-To: <400BDC416E2A0042AA35DF3919BB8A5115E64F@mail.mtl.proksim.com> References: <400BDC416E2A0042AA35DF3919BB8A5115E64F@mail.mtl.proksim.com> Message-ID: Olivier Langlois wrote: > Hi Michael! > > Your suggestion is fantastic and is doing exactly what I was looking > for! Thank you very much. > There is something that I'm wondering though. Why is the solution you > proposed wouldn't work with Unicode strings? > Simply, that str.translate with two arguments isn't implemented for unicode strings. I don't know the underlying reason, or how hard it would be to change. If you do need the comparison functionality for unicode strings, you'll have to go with a different approach. For example, using regular expressions: import re def compare2(a, b): """Compare two basestrings, disregarding whitespace -> bool""" return re.sub("\s*", "", a) == re.sub("\s*", "", b) This is slower than the str.translate approach, though it has the advantage that you could easily modify it to normalize, rather than eliminate whitespace. This would be a more useful comparison in many cases. def compare3(a, b): """Compare two basestrings, normalizing whitespace -> bool""" return re.sub("\s*", " ", a) == re.sub("\s*", " ", b) Continuing the disclaimers: none these approaches makes any attempt to deal specially with quoted whitespace or any other sort of escapes. Michael From johnjsal at NOSPAMgmail.com Sun Mar 12 19:28:43 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 12 Mar 2006 19:28:43 -0500 Subject: how exactly do binary files work in python? Message-ID: In C#, writing to a binary file wrote the actual data types into the file (integers, etc.). Is this not how Python binary files work? I tried to write integers into a file, but the write method only takes a string argument anyway. Is there a way to actually store integers in a file, so that they can be read and used (added, compared, etc.) as integers? From jstroud at ucla.edu Sun Mar 5 20:38:48 2006 From: jstroud at ucla.edu (James Stroud) Date: Sun, 05 Mar 2006 17:38:48 -0800 Subject: searching for the number of occurences of a string In-Reply-To: References: Message-ID: M.N.A.Smadi wrote: > hi; > say i have a text file with a string ( say '(XYZ)') and I want to find > the number of line where this string has occured. What is the best way > to do that? > > what about if that string was say a 0 with leading and trailing white > spaces, would that be any different? > > thanks > moe smadi To read every line in a file: afile = open(filename) for aline in afile: do_something_here() afile.close() To see if a string contains another string, try if another_string in astring: do_something_else_here() If you need regular expressions, see the re module. For instance: import re regex = re.compile(r'(?:\s+0\s+)|\(XYZ\)') print regex.search(' 0 ').group() print regex.search(' (XYZ) abc').group() if regex.search('abcdefg'): print 'yep' else: print 'nope' That should be everything you could possibly need. Its up to you to put it all together. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From linuxnooby at yahoo.com.au Thu Mar 30 18:11:19 2006 From: linuxnooby at yahoo.com.au (linuxnooby at yahoo.com.au) Date: 30 Mar 2006 15:11:19 -0800 Subject: tkinter question In-Reply-To: References: <1143501305.697282.283180@t31g2000cwb.googlegroups.com> <1143670082.175804.317850@t31g2000cwb.googlegroups.com> Message-ID: <1143760279.774693.61460@j33g2000cwa.googlegroups.com> >If you just create >a Toplevel and populate it with widgets, it will just display once the >control is returned to the Tkinter mainloop and no user input will be >needed. Thanks for explaining that. I borrowed the "after" method that you used in your first reply. It seems to do what I want (except for root.destroy) Though any suggestions on a more elegant solution welcome. cheers David from Tkinter import * def message1(): top1 = Tk() F1 = Frame(top1) F1.pack() Hello1 = Label(F1, text="step 2 you will be logged off in 5 seconds") Hello1.pack() top1.after(3000, message2) def message2(): top2 = Tk() F2 = Frame(top2) F2.pack() Hello2 = Label(F2, text="step 3 you will be logged off in 2 seconds") Hello2.pack() top2.after(2000, goodbye) def goodbye(): print "step 4 you are logged out" root.destroy root = Tk() root.withdraw() print "step 1 login window withdrawn" message1() root.mainloop() From tiit at sympatico.ca Fri Mar 3 14:57:41 2006 From: tiit at sympatico.ca (Etienne Desautels) Date: Fri, 3 Mar 2006 14:57:41 -0500 Subject: [Python-Help] Reading from socket file handle took too long In-Reply-To: <1141148544.69.491@mint-julep.mondoinfo.com> References: <1141148544.69.491@mint-julep.mondoinfo.com> Message-ID: Hi, thanks Matthew for the answer. It help me think a little bit more. I found a solution and I think I found the culprit but I would need to do more investigation to be sure. My solution is to work directly with the socket library instead of using the higher level urllib2 library. Now it take only around 0,005 s. to read and process each chunk of data (a chunk is the data that arrived in the last 1/24 s.) instead of between 0,04 s. and 0,1 s.. That's a lot faster! I think the real culprit for slowing this process is in the httplib that urllib2 is using, and the problem come probably from the way httplib read from the socket. It look httplib have some problem reading when there's no EOF or something like that. Etienne On 06-02-28, at 12:58, Matthew Dixon Cowles wrote: > Dear Etienne, > >> Hi, > > Hi! > >> I monitor every call and I found that the culprit is when I read >> from the socket file handle. It's the only bottleneck in my code. I >> try different approaches to the problem but I always hit the same >> problem. > >> I don't think it's normal that read() take more then 0,04 sec to >> read 1000 bytes from memory (the socket file handle). How can I >> avoid this problem ? > >> temp = self.fh.read(self.limit) # <-- TAKE A LOT OF TIME > > I agree with you that reading 1000 bytes from a socket shouldn't take > that long. Especially since it should really amount to copying the > data from one buffer to another. > > It's just a guess, but I would suspect that the reason that it takes > that long to read a particular amount of data from the socket is that > there isn't that much data available when you start the read. > > It ought to be easy enough to check that by reducing the amount you > try to read by a lot and seeing if the call finishes a lot faster. > > If that turns out to be what's slowing you down, it might be useful > to separate the job of reading from the job of decoding and doing > whatever else you need to do with the data. To me, the obvious way to > try to do that would be with threads. I've never used Twisted, but I > imagine that it provides some mechanism for something like that. > > I hope that other folks here will also answer if they have a guess > about what's happening. > > Regards, > Matt > From bencvt at gmail.com Fri Mar 10 01:25:06 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 9 Mar 2006 22:25:06 -0800 Subject: counting number of (overlapping) occurances References: <1141968108.977332.261010@i40g2000cwc.googlegroups.com> <7x3bhq7tf0.fsf@ruckus.brouhaha.com> <1141970477.071343.160300@j52g2000cwj.googlegroups.com> Message-ID: <1141971906.040689.179020@i40g2000cwc.googlegroups.com> John wrote: > This works but is a bit slow, I guess I'll have to live with it. > Any chance this could be sped up in python? Sure, to a point. Instead of: def countoverlap(s1, s2): return len([1 for i in xrange(len(s1)) if s1[i:].startswith(s2)]) Try this version, which takes smaller slices (resulting in 2x-5x speed increase when dealing with a large s1 and a small s2): def countoverlap(s1, s2): L = len(s2) return len([1 for i in xrange(len(s1)-L+1) if s1[i:i+L] == s2]) And for a minor extra boost, this version eliminates the list comprehension: def countoverlap(s1, s2): L = len(s2) cnt = 0 for i in xrange(len(s1)-L+1): if s1[i:i+L] == s2: cnt += 1 return cnt Finally, if the execution speed of this function is vital to your application, create a C extension. String functions like this one are generally excellent candidates for extensionizing. --Ben From deets at nospam.web.de Tue Mar 21 11:59:01 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 21 Mar 2006 17:59:01 +0100 Subject: Can XML-RPC performance be improved? References: Message-ID: <48apnrFj7ambU1@uni-berlin.de> Sion Arrowsmith wrote: > I've got an established client-server application here where there > is now a need to shovel huge amounts of data (structured as lists of > lists) between the two, and the performance bottleneck has become > the amount of time spent parsing XML (it's taking 100% CPU on one or > other end of the connection and accounting for well over 50% of the > total call time, to the extent that it's having a greater impact on > performance than user interaction). And this is using SGMLOP for > parsing -- I dread to think what it would be like with a slower > parser. Anyone (Fredrik?) got any good ideas for tackling this > problem? CORBA. Or TCP/IP directly. I know that isn't really the answer you're looking for - but there is an overhead parsing XML, and that can't go away. >From what I read at SGMLOP's site I doub't that you can get much faster - because speed comes with sacrificing standard compliancy, which it already seems to do. Regards, Diez From john_zenger at yahoo.com Wed Mar 1 20:10:33 2006 From: john_zenger at yahoo.com (John Zenger) Date: Wed, 01 Mar 2006 20:10:33 -0500 Subject: newbie question In-Reply-To: <1141242700.105093.317210@t39g2000cwt.googlegroups.com> References: <1141242700.105093.317210@t39g2000cwt.googlegroups.com> Message-ID: orangeDinosaur wrote: > I wrote up a script in my preferred text editor. It contains maybe ten > lines of code. I want to be able to execute those code lines with a > single command either from the inline mode or from IDLE. How do I do > this? I saved the file (myscript.py) in a folder that I've specified > in my PYTHONPATH environment variable, and when I type From the Python shell, you can use execfile to run a script: >>> execfile("joshua.py") This works regardless of your OS. The file must be in your Python path. If it isn't, just specify the full path. Like: >>> execfile(r"C:\Code\WOPR\Backdoor\joshua.py") While viewing your code with IDLE, hit F5 to execute it. From hancock at anansispaceworks.com Tue Mar 7 19:12:08 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 7 Mar 2006 18:12:08 -0600 Subject: Learning different languages In-Reply-To: References: Message-ID: <200603071812.08540.hancock@anansispaceworks.com> On Tuesday 07 March 2006 04:44 pm, Rich wrote: > Anyway, my question is: what experience you people have with working > with different languages at the same time? Invariably, you will occasionally confuse one with the other, which is a penalty you already know, I'm sure. OTOH, it will reduce your bias towards the limitations of one language over another. I've been trying to get my kids to learn a little Python for some time, but it hasn't been too easy for them yet. Then, out of the blue, they want to learn Lua. Why? Simple -- Lua is the extension language for Enigma. So they want to make new game levels ergo, they must use Lua. Motivation matters more than ease, IMHO. :-) We realized recently that while teaching kids to program is hard, teaching them to *hack* is easy. Once they learn to hack game levels, they will learn, from the level designers, basics about scripting and then programming, and they'll start to ask "how can I make this easier?" Already, my son asked "is there any way I don't have to type this line over and over again?" So we learned loops that day. It is SO much easier to teach a concept when the student is actively trying to find out, instead of trying to push the idea on them and come up with justification for why they need to know it. This way he already knows the problem -- I just have to provide the solution. But I don't think I want to try to go full-force into Lua. In some ways it's similar to Python, but lighter-weight. OTOH, I don't think I'd want to try to make anything serious with it. Nevertheless, I find that it's easier to teach them Python at the same time as they learn Lua. Concepts are similar, and it's not really that hard to go back and forth. I'm going to continue developing basic concepts in Lua (embedded in Enigma), and then work with Python and PyGame to get them making their own programs from scratch using the concepts they learn through hacking (a project we've been interested in for some time -- my kids have been making sprites for a future game for a long time now and are getting pretty good at that part). So, I don't think you'll have a real problem with it. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From jstroud at ucla.edu Mon Mar 27 21:43:33 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 27 Mar 2006 18:43:33 -0800 Subject: what is the the best way to express following: In-Reply-To: <_uOdnaBMCLmcPLXZRVn-uA@comcast.com> References: <_uOdnaBMCLmcPLXZRVn-uA@comcast.com> Message-ID: AndyL wrote: > if type(key).__name__ == "int" or type(key).__name__ == "long": > abc() > elif type(key).__name__ == "str": > efg() > elif type(key).__name__ == "tuple" or type(key).__name__ == "list": > ijk() > > > In other words I need to determinie intiger type or string or []/() in > elegant way, possibly without or ... > > Thx, A. Here is a suggestion todo = {(int, long):abc, (str,):afg, (tuple, list):ijk} todo[type(key)]() James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From johnjsal at NOSPAMgmail.com Tue Mar 7 11:01:18 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 07 Mar 2006 16:01:18 GMT Subject: inserting into a list In-Reply-To: <475nd6Fe08fsU1@uni-berlin.de> References: <475nd6Fe08fsU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >>>> l = [1,2,3] >>>> l.insert(2, 10) >>>> l > [1, 2, 10, 3] > > Embarrasing enough? Actually, I was trying to figure it out with the slice technique instead. But yeah, as Christopher's example showed, it's not hard. But I didn't realize you had to assign a list item to the slice, so I was doing: L[2:2] = 3 among other things, but they all involved '= 3', not '= [3]' From claudio.grondi at freenet.de Wed Mar 1 11:04:50 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 01 Mar 2006 17:04:50 +0100 Subject: Searching for uniqness in a list of data In-Reply-To: <1141228140.331259.8060@j33g2000cwa.googlegroups.com> References: <1141228140.331259.8060@j33g2000cwa.googlegroups.com> Message-ID: rh0dium wrote: > Hi all, > > I am having a bit of difficulty in figuring out an efficient way to > split up my data and identify the unique pieces of it. > > list=['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8_sal_log'] > > Now I want to split each item up on the "_" and compare it with all > others on the list, if there is a difference I want to create a list of > the possible choices, and ask the user which choice of the list they > want. I have the questioning part under control. I can't seem to get > my hands around the logic - the list could be 2 items or 100 long. The > point of this is that I am trying to narrow a decision down for an end > user. In other words the end user needs to select one of the list > items, and by breaking it down for them I hope to simplify this. > > list=['1p2m_3.3-1.8v_sal_ms','1p6m_3.3-1.8_sal_log'] > would only question the first data set ['1p2m', '1p6m' ] > > list=['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8v_pol_ms','1p3m_3.3-18.v_sal_ms'] > If on the list ['1p2m','1p2m','1p3m'] the user selected 1p2m then the > next list would only be ['sal','pol'] > but if the user initially only selected 1p3m they would be done.. > > I hope this clarifies what I am trying to do. I just can't seem to get > my hands around this - so an explaination of logic would really be > helpfull. I picture a 2d list but I can't seem to get it.. > list=['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8v_pol_ms','1p3m_3.3-18.v_sal_ms'] dictQlevel_1={} dictQlevel_2={} dictQlevel_3={} for item in list: splitted = item.split('_') dictQlevel_1[splitted[0]] = True dictQlevel_2[splitted[1]] = True dictQlevel_3[splitted[2]] = True print 'choose one of: ' for key_1 in dictQlevel_1.keys(): print key_1 print usrInput = raw_input() if usrInput == '': print 'choose one of: ' for key_1 in dictQlevel_1.keys(): for key_2 in dictQlevel_2.keys(): print key_1, key_2 print usrInput = raw_input() else: pass # or do something # etc. Hope it is what you are looking for. Claudio From steven.bethard at gmail.com Wed Mar 15 11:30:15 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 15 Mar 2006 09:30:15 -0700 Subject: stdin or optional fileinput In-Reply-To: <1142439653.706305.134290@j33g2000cwa.googlegroups.com> References: <1142439653.706305.134290@j33g2000cwa.googlegroups.com> Message-ID: the.theorist wrote: > I was writing a small script the other day with the following CLI > prog [options] [file]* > > I've used getopt to parse out the possible options, so we'll ignore > that part, and assume for the rest of the discussion that args is a > list of file names (if any provided). > > I used this bit of code to detect wether i want stdinput or not. > > if len(args)==0: > args = [ sys.stdin ] > > Now in my main loop I've written: > > for file in args: > for line in open( file ): > #do stuff You should probably write: if not args: # note that len(args) == 0 is repetitively redundant, over # and over again, in a reiterative manner files = [sys.stdin] else: files = (open(filename) for filename in args) ... for fileobj in files: # using the name 'file' is a bad idea since it # shadows the builtin 'file' for line in fileobj: # do stuff STeVe From silverburgh.meryl at gmail.com Fri Mar 10 12:10:41 2006 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: 10 Mar 2006 09:10:41 -0800 Subject: Use python to process XML file Message-ID: <1142010641.770379.229230@j52g2000cwj.googlegroups.com> Hi, Can you please tell me how Use python to process XML file? The example I find is build a DOM, but I just need to do it in SAX based, how can I do that? For example, I have a xml file like this: text text text text text text text For i want to process the node in the order they appears. If element name == 'a' do this else If element name == 'b' do this else If element name == 'c' do this From jao at geophile.com Wed Mar 8 15:18:04 2006 From: jao at geophile.com (jao at geophile.com) Date: Wed, 08 Mar 2006 15:18:04 -0500 Subject: using PyShell, or other shells? In-Reply-To: References: Message-ID: <20060308151804.rf1kqepi8gwkcsko@geophile.com> Quoting John Salerno : > I'm interested in trying out shells other than IDLE, and I found > PyShell, but I'm not sure how to get it exactly. Is there a way to get > it without installing wxPython, or is it a part of it? I can't find much > reference to it in any of the manuals at wxpython.org (except for a > brief description of what it is, but not *where* it is or how to use it). > > Thanks. And if there are other shells that are newer/better, I'd > appreciate a recommendation. If you're interested in shell-like capabilities inside a Python environment, check out IPython: http://ipython.scipy.org. If you want Python-like capabilities from a traditional shell, check out osh: http://geophile.com/osh. (Disclaimer: I am the developer of osh.) Jack Orenstein From heathimself at gmail.com Thu Mar 16 19:23:48 2006 From: heathimself at gmail.com (heathimself at gmail.com) Date: 16 Mar 2006 16:23:48 -0800 Subject: Converting to ARGB and writing to a bitmap Message-ID: <1142555028.430564.4320@p10g2000cwp.googlegroups.com> Hi, I don't know what type of files they are, but the script allows me to save to a bitmap just fine. But I do know they need to be in RGBA 4444 format, so I've followed what most of the tutorials for RGBA conversions said to do...shifting the bytes. The major problem is that everything is in green, it's shifted up by x pixels, and it's..um..flipped from left to right. I've been working on this for a few weeks now and any insight to the problem is greatly appreciated. http://www.geocities.com/fisherdude_99/TestImg.zip import struct import sys import Image if len(sys.argv) < 3: print "usage: tobmp.py " sys.exit(1) width = int(sys.argv[2]) f1 = open(sys.argv[1], "rb") f1.seek(0, 2) size = f1.tell() f1.seek(0) ### write BITMAPFILEHEADER ### f2 = open(sys.argv[1] + ".bmp", "wb") f2.write("BM") bfSize = size+54 f2.write(struct.pack("L", bfSize)) # bfReserved1 and 2 f2.write("\x00\x00\x00\x00") bfOffBits = 54 f2.write(struct.pack("L", bfOffBits)) ### write BITMAPINFOHEADER ### biSize = 40 f2.write(struct.pack("L", biSize)) biWidth = width f2.write(struct.pack("L", biWidth)) biHeight = (size/ 2/ width) f2.write(struct.pack("L", biHeight)) biPlanes = 1 f2.write(struct.pack("H", biPlanes)) biBitCount = 32 f2.write(struct.pack("H", biBitCount)) # biCompression f2.write("\x00\x00\x00\x00") # biSizeImage f2.write("\x00\x00\x00\x00") # biXPelsPerMeter f2.write("\x00\x00\x00\x00") # biYPelsPerMeter f2.write("\x00\x00\x00\x00") # biClrUsed f2.write("\x00\x00\x00\x00") # biClrImportant f2.write("\x00\x00\x00\x00") ### write the bitmap data ### print f2.tell() ##must be 54 # since bitmaps are upside down, gotta flip it over data = f2.read() i = size-21 while i >= 0: nm = 0x100 f1.seek(i) temp1 = struct.unpack('B', f1.read(1))[0] peek = temp1 a = nm*(peek >> 24) & 0xff r = nm*(peek >> 16) & 0xff g = nm*(peek >> 8 ) & 0xff b = nm*(peek & 0xff) sh = (a<<24)|(r<<16)|(g<<8)|b f2.write(struct.pack('H', sh)) i -= 1 f1.close() f2.close() Usage: bmpcon.py testimg 100 Thanks a lot From JordanGreenberg at gmail.com Wed Mar 22 16:32:37 2006 From: JordanGreenberg at gmail.com (Jordan Greenberg) Date: 22 Mar 2006 13:32:37 -0800 Subject: Getting a loop to activate a loop above it In-Reply-To: <1143061653.100159.127550@u72g2000cwu.googlegroups.com> References: <1143061653.100159.127550@u72g2000cwu.googlegroups.com> Message-ID: <1143063157.042592.103280@j33g2000cwa.googlegroups.com> x=1 while not x==3: if x==1: print 'hello' x = input('what is x now?: ') if x==2: print 'hello again' x=input('what is x now?: ') any code you want to repeat needs to be in some sort of a loop structure. Program execution doesn't just jump around unless you tell it to. -- Jordan T. Greenberg Spork Polisher From danbrwn at gmail.com Wed Mar 29 12:06:07 2006 From: danbrwn at gmail.com (Dan) Date: 29 Mar 2006 09:06:07 -0800 Subject: Creating COM server Events? Message-ID: <1143651967.693545.40010@i40g2000cwc.googlegroups.com> I have need to create a com server that will fire events back to clients. I have looked at some of the documentation and I am new to Python so cant quite get it. I have created an IDL file of the interfaces. Can someone tell me approximately what needs to be done here. I have seen examples of implementing the regular interfaces but don't know what to do about the events interfaces.The vid...Events interface is the main question here. In regular com development you would implement something along the lines of Fire_OnNewData(). My Com developement has mostly been with Borland tools and they do quite a bit for you, As I hope Python will. Heres the IDL: [ uuid(B0ADD4E1-1793-4089-8298-20B5A2DB0E82), version(1.0), helpstring("vidVisPython Library") ] library vidVisPython { importlib("stdole2.tlb"); [ uuid(E26E3023-4F65-4E3D-A900-56C6302CD4E0), version(1.0), dual, oleautomation ] interface IVideoVisitationPython: IDispatch { [ id(0x00000001) ] HRESULT _stdcall AdviseNewData( void ); }; [ uuid(50A02634-215F-47C6-9749-CDD02DC99B13), version(1.0) ] dispinterface IVideoVisitationPythonEvents { properties: methods: [ id(0x00000001) ] HRESULT OnNewData( void ); }; [ uuid(134821F5-35B9-4917-B6EE-EF5C508BE949), version(1.0) ] coclass CoVideoVisitationPython { [default] interface IVideoVisitationPython; [default, source] dispinterface IVideoVisitationPythonEvents; }; }; From vinjvinj at gmail.com Tue Mar 28 10:44:59 2006 From: vinjvinj at gmail.com (vj) Date: 28 Mar 2006 07:44:59 -0800 Subject: how to use ez_setup on a machine which does not have access to the internet Message-ID: <1143560699.160953.10500@i39g2000cwa.googlegroups.com> I did the following: 1. Downloaded ez_setup.py 2. Downloaded the setuptools-0.6a10-py2.4.egg 3. Downloaded the pysqlite-2.0.6-py2.4-linux-i686(2).egg Transferred all the files to the computer which is behind a firewall (with no access to the internet). I then did the following: path_to_python ez_setup.py setuptools-0.6a10-py2.4.egg it failed even though the setuptools-0.6a10-py2.4.egg was in the same directory. It gives me an error: urllib2.URLError: <441c779a$1@nntp0.pdx.net> Message-ID: In article <441c779a$1 at nntp0.pdx.net>, Scott David Daniels wrote: > Roy Smith wrote: > > I never understood why people switch mouse buttons. I'm left handed, so I > > put the mouse on the left side of my keyboard. It never occurred to me to > > flip the buttons around. > Well, I switch 'em because the "forefinger is primary" is ingrained. I do both buttons with my forefinger. It just seems like the normal thing to do. From fabiofz at gmail.com Fri Mar 31 10:23:50 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Fri, 31 Mar 2006 12:23:50 -0300 Subject: Best IDE for Python? In-Reply-To: <1143816395.190171.298530@t31g2000cwb.googlegroups.com> References: <1143783179.361616.76750@i39g2000cwa.googlegroups.com> <1143813623.203852.184000@g10g2000cwb.googlegroups.com> <1143816395.190171.298530@t31g2000cwb.googlegroups.com> Message-ID: On 31 Mar 2006 06:46:35 -0800, kbperry wrote: > > I have recently been trying out NewEdit, and it is a pretty good "IDE" > for Python. > > The reason that I have it in quotes is because I haven't really found a > true IDE (like the way Eclipse behaves for Java) for python. (I > realize that Eclipse has a plug-in for Python, too). So, why wouldn't you consider Pydev (the python plugin for Eclipse) a Python IDE? -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Wed Mar 8 09:33:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 8 Mar 2006 15:33:55 +0100 Subject: recycling internationalized garbage References: <1141827739.823228.198160@j33g2000cwa.googlegroups.com> Message-ID: "aaronwmail-usenet at yahoo.com" wrote: > Question: what is a good strategy for taking an 8bit > string of unknown encoding and recovering the largest > amount of reasonable information from it (translated to > utf8 if needed)? The string might be in any of the > myriad encodings that predate unicode. Has anyone > done this in Python already? The output must be clean > utf8 suitable for arbitrary xml parsers. some alternatives: braindead bruteforce: try to do strict decoding as utf-8. if you succeed, you have an utf-8 string. if not, assume iso-8859-1. slightly smarter bruteforce: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/163743 more advanced (but possibly not good enough for very short texts): http://chardet.feedparser.org/ From michele.simionato at gmail.com Thu Mar 23 10:22:38 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 23 Mar 2006 07:22:38 -0800 Subject: Strange metaclass behaviour In-Reply-To: References: Message-ID: <1143127358.820526.259930@i40g2000cwc.googlegroups.com> Christian Eder wrote: > Hi, > > I think I have discovered a problem in context of > metaclasses and multiple inheritance in python 2.4, > which I could finally reduce to a simple example: > > Look at following code: > > class M_A (type) : > > def __new__ (meta, name, bases, dict) : > print "M.__new__", meta, name, bases > return super (M_A, meta).__new__ (meta, name, bases, dict) > > class M_B (M_A) : pass > > class A (object) : __metaclass__ = M_A > > class B (object) : __metaclass__ = M_B > > class D (A, B) : pass > > > One would expect that either > 1) D inherits the metaclass M_A from A > 2) or python raises the well known "Metatype conflict among bases" > error No, there is no conflict in this case: since M_B is a subclass of M_A, the metaclass of D is M_B. I don't think this is bug either: the fact is that type.__new__ works differently from object.__new__, so that it is called twice in this case. Not sure if it could be avoided. Speaking of the metatype conflict, I realized a while ago that it is possible to avoid it automatically even at the pure Python level, without changing the C code for type.__new__. However, the solution is too complicate. According to the Zen of Python "If the implementation is hard to explain, it's a bad idea", thus I have never used it. Still, it is an interesting exercise if you are willing to risk the melting of your brain, so here is the code ;) # noconflict.py """Deep, **DEEP** magic to remove metaclass conflicts. ``noconflict`` provides the ``safetype`` metaclass, the mother of conflict-free metaclasses. I you do from noconflict import safetype as type on top of your module, all your metaclasses will be conflict safe. If you override ``__new__`` when you derive from ``safetype``, you should do it cooperatively.""" import inspect, types, __builtin__ try: set # python version >= 2.4 except NameError: # python version <= 2.3 from sets import Set as set def skip_redundant(iterable, skipset=None): "Redundant items are repeated items or items in the original skipset." if skipset is None: skipset = set() for item in iterable: if item not in skipset: skipset.add(item) yield item memoized_metaclasses_map = {} # utility function def remove_redundant(metaclasses): skipset = set([types.ClassType]) for meta in metaclasses: # determines the metaclasses to be skipped skipset.update(inspect.getmro(meta)[1:]) return tuple(skip_redundant(metaclasses, skipset)) ################################################################## ## now the core of the module: two mutually recursive functions ## ################################################################## def get_noconflict_metaclass(bases, left_metas, right_metas): """Not intended to be used outside of this module, unless you know what you are doing.""" # make tuple of needed metaclasses in specified priority order metas = left_metas + tuple(map(type, bases)) + right_metas needed_metas = remove_redundant(metas) # return existing confict-solving meta, if any if needed_metas in memoized_metaclasses_map: return memoized_metaclasses_map[needed_metas] # nope: compute, memoize and return needed conflict-solving meta elif not needed_metas: # wee, a trivial case, happy us meta = type elif len(needed_metas) == 1: # another trivial case meta = needed_metas[0] # check for recursion, can happen i.e. for Zope ExtensionClasses elif needed_metas == bases: raise TypeError("Incompatible root metatypes", needed_metas) else: # gotta work ... metaname = '_' + ''.join([m.__name__ for m in needed_metas]) meta = classmaker()(metaname, needed_metas, {}) memoized_metaclasses_map[needed_metas] = meta return meta def classmaker(left_metas=(), right_metas=()): def make_class(name, bases, adict): metaclass = get_noconflict_metaclass(bases, left_metas, right_metas) return metaclass(name, bases, adict) return make_class ################################################################# ## and now a conflict-safe replacement for 'type' ## ################################################################# __type__=__builtin__.type # the aboriginal 'type' # left available in case you decide to rebind __builtin__.type class safetype(__type__): """Overrides the ``__new__`` method of the ``type`` metaclass, making the generation of classes conflict-proof.""" def __new__(mcl, *args): nargs = len(args) if nargs == 1: # works as __builtin__.type return __type__(args[0]) elif nargs == 3: # creates the class using the appropriate metaclass n, b, d = args # name, bases and dictionary meta = get_noconflict_metaclass(b, (mcl,), right_metas=()) if meta is mcl: # meta is trivial, dispatch to the default __new__ return super(safetype, mcl).__new__(mcl, n, b, d) else: # non-trivial metaclass, dispatch to the right __new__ # (it will take a second round) return super(mcl, meta).__new__(meta, n, b, d) else: raise TypeError('%s() takes 1 or 3 arguments' % mcl.__name__) Michele Simionato From matt at pollenation.net Mon Mar 20 17:24:38 2006 From: matt at pollenation.net (Matt Goodall) Date: Mon, 20 Mar 2006 22:24:38 +0000 Subject: why isn't Unicode the default encoding? In-Reply-To: References: <441F21D7.6000005@v.loewis.de> Message-ID: <441F2BA6.1040800@pollenation.net> John Salerno wrote: > Martin v. L?wis wrote: > >> The real problem is that the Python string type is used to represent >> two very different concepts: bytes, and characters. You can't just drop >> the current Python string type, and use the Unicode type instead - then >> you would have no good way to represent sequences of bytes anymore. >> Byte sequences occur more often than you might think: a ZIP file, a >> MS Word file, a PDF file, and even an HTTP conversation are represented >> through byte sequences. >> >> So for a byte sequence, internal representation is important; for a >> character string, it is not. Now, for historical reasons, the Python >> string literals create byte strings, not character strings. Since we >> cannot know whether a certain string literal is meant to denote bytes >> or characters, we can't just change the interpretation. > > Interesting. So then the read() method, if given a numeric argument for > bytes to read, would act differently depending on if you were using > Unicode or not? As it is now, it seems to equate the bytes with number > of characters, but if the document was written using Unicode characters, > is it possible that read(2) might only pull out one character? Exactly. read(2) might pull out one character, or only half a character. It all depends on the encoding of the data you're reading. If you're reading or writing text to a file (or anywhere, for that matter) you need to know the unicode encoding of the file's content to read it correctly. Fortunately, the codecs module makes the whole process relatively painless: >>> import codecs >>> f = open("a_utf8_encoded_file.txt") >>> stream = codecs.getreader('utf-8')(f) >>> c = stream.read(1) The 'stream' works on unicode characters so 'c' is a unicode instance, i.e. a whole textual character. - Matt -- __ / \__ Matt Goodall, Pollenation Internet Ltd \__/ \ w: http://www.pollenation.net __/ \__/ e: matt at pollenation.net / \__/ \ t: +44 (0)113 2252500 \__/ \__/ / \ Any views expressed are my own and do not necessarily \__/ reflect the views of my employer. From danderup at yahoo.com Thu Mar 16 19:10:07 2006 From: danderup at yahoo.com (Gates Danderhoff) Date: 17 Mar 2006 00:10:07 -0000 Subject: python newbie, linux novice, needs to run spamassassin Message-ID: The frustrating thing about running linux is that every time you look for an example using a search engine, the guy writing it expects you to know 10 other utilities. I have a very simple request regarding spamassain: I just need an example of how to run it once you have downloaded one or more emails into a folder. I have a python script which runs poplib and is downloading emails into a folder, say ~/mymailin. Each time the script is run and emails have been downloaded into the folder, I would like to run spamassassin to read through the emails in the folder and check them for their spamminess and if they are spammy, it should do whatever spamassassin does: add a header and move it to another folder, say ~/myspam, or maybe ~/mygoodemail if it's not spammy? There must be a simple spamassassin command that will do this, that I can add to the python script and run using the cmdline.... facility, but, as I say, all the examples I've seen have something to do with running spamassassin with procmail, fetchmail, qmail and God knows what else. Some day I'll learn all about procmail, but, for now, I like my little python poplib script, and a simple spamassassin example should do the trick. Thank you for any help. From tjreedy at udel.edu Thu Mar 30 18:55:40 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 30 Mar 2006 18:55:40 -0500 Subject: RELEASED Python 2.4.3, final. References: Message-ID: "John Salerno" wrote in message news:mJSWf.1860$No6.42010 at news.tufts.edu... > Why would 2.4.4 come out after the final release of 2.5? Code patches are generally applied first to the development branch. Those that merely fix bugs usually get backported to the maintenance branch.* Releasing 2.4.4 after 2.5 has two purposes. One, as Fredrik said, is to catch up on the backlog of backports, which may grow in the final rush to get the new version out. It also gives additional time to test all the bugfixes in wider usage than the test suite. Terry Jan Reedy From paddy3118 at netscape.net Thu Mar 2 16:35:39 2006 From: paddy3118 at netscape.net (Paddy) Date: 2 Mar 2006 13:35:39 -0800 Subject: Shared memory In-Reply-To: References: Message-ID: <1141335339.714536.316590@i40g2000cwc.googlegroups.com> Pylinda ? http://www-users.cs.york.ac.uk/~aw/pylinda/ From turian at gmail.com Tue Mar 21 17:05:49 2006 From: turian at gmail.com (Joseph Turian) Date: 21 Mar 2006 14:05:49 -0800 Subject: Importing two module variables and having one clobber the other? In-Reply-To: References: <1142971896.080149.144080@v46g2000cwv.googlegroups.com> Message-ID: <1142978749.016857.4130@v46g2000cwv.googlegroups.com> Fredrik Lundh wrote: > if you prefer to use a "parameters.value" syntax, you can wrap the resulting > dictionary in a class. That sounds good. How do I do that? > I assume "from" means "beneath" and "getcwd" means "walk" ? Actually: def superdirs(d): lst = [d] while d != os.environ["HOME"]: (d, tl) = os.path.split(d) lst += [d] lst.reverse() return lst Joseph From kbk at shore.net Tue Mar 28 23:59:16 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Tue, 28 Mar 2006 23:59:16 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200603290459.k2T4xG9n011371@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 389 open ( -3) / 3117 closed (+23) / 3506 total (+20) Bugs : 901 open ( -6) / 5687 closed (+41) / 6588 total (+35) RFE : 214 open ( +1) / 206 closed ( +4) / 420 total ( +5) New / Reopened Patches ______________________ Minimalist fix for bug 1446847 (2006-03-17) CLOSED http://python.org/sf/1452332 opened by Nick Coghlan N-d array interface for array object (2006-03-17) http://python.org/sf/1452906 opened by Alexander Belopolsky IDNA codec simplification (2006-03-18) http://python.org/sf/1453235 opened by Walter D?rwald popen2 new parameter and setpgid (2006-03-20) CLOSED http://python.org/sf/1454425 opened by Oskar Ander? 2 Tools for easy inter-thread communication->Queue,threading (2006-03-20) http://python.org/sf/1454452 opened by kxroberto Make thread stack size runtime tunable (2006-03-20) http://python.org/sf/1454481 opened by Andrew I MacIntyre patch for SIGSEGV in arraymodule.c (2006-03-20) http://python.org/sf/1454485 reopened by tbmetin patch for SIGSEGV in arraymodule.c (2006-03-20) http://python.org/sf/1454485 opened by Baris Metin Use dlopen() to load extensions on Darwin, where possible (2006-03-20) http://python.org/sf/1454844 opened by Zach Pincus patch for mbcs codecs (2006-03-22) http://python.org/sf/1455898 opened by ocean-city timestamp() method for datetime objects (2006-03-23) CLOSED http://python.org/sf/1457227 opened by Chris AtLee Support different GPG keys in upload --sign (2006-03-23) http://python.org/sf/1457316 opened by Stefan Behnel patch for building trunk with VC6 (2006-03-24) http://python.org/sf/1457736 opened by ocean-city floor division (2006-03-25) CLOSED http://python.org/sf/1458419 opened by Andy Improved PySet C API (2006-03-25) CLOSED http://python.org/sf/1458476 opened by Barry A. Warsaw Mutable Iterators PEP (2006-03-26) http://python.org/sf/1459011 opened by Adam DePrince Install PKG-INFO with packages (2006-03-27) http://python.org/sf/1459476 opened by Phillip J. Eby Add docs for zlib.decompressobj.flush optional param (2006-03-27) CLOSED http://python.org/sf/1459630 opened by Chris AtLee Update docs for zlib.decompressobj.flush() (2006-03-27) http://python.org/sf/1459631 opened by Chris AtLee convenient Message.as_string to use mangle_from_=unixfrom ? (2006-03-28) http://python.org/sf/1459867 opened by kxroberto Patches Closed ______________ PEP 338 implementation (2006-02-11) http://python.org/sf/1429601 closed by ncoghlan patch for 1441408 compiler fails to spot extended slice (2006-03-10) http://python.org/sf/1446847 closed by ncoghlan Minimalist fix for bug 1441408 (2006-03-17) http://python.org/sf/1452332 closed by ncoghlan PEP 338 documentation (2006-02-11) http://python.org/sf/1429605 closed by ncoghlan error checking after PyXXX_New (2006-03-08) http://python.org/sf/1445505 closed by gbrandl audioop - alaw encoding/decoding added, code updated (2005-07-02) http://python.org/sf/1231053 closed by anthonybaxter Method for cell objects to access contents (2005-03-25) http://python.org/sf/1170323 closed by gbrandl Incremental codecs for CJKCodecs (2006-03-05) http://python.org/sf/1443155 closed by perky A wait4() implementation (2005-09-30) http://python.org/sf/1309579 closed by nnorwitz Make itertools.tee participate in GC (2006-03-06) http://python.org/sf/1444398 closed by twouters more leaky, leaky (2006-03-07) http://python.org/sf/1445431 closed by nnorwitz Some fixes for the binary distribution builder (2005-12-14) http://python.org/sf/1380777 closed by ronaldoussoren popen2 new parameter and setpgid (2006-03-20) http://python.org/sf/1454425 closed by oskar_andero CALL_ATTR opcode (2003-03-26) http://python.org/sf/709744 closed by twouters FreeBSD is system scope threads capable (2006-01-04) http://python.org/sf/1396919 closed by perky timestamp() method for datetime objects (2006-03-23) http://python.org/sf/1457227 closed by gvanrossum Add method to function objects to simplify decoration (2005-03-12) http://python.org/sf/1161819 closed by ncoghlan Simplify using Queues with consumer threads (2006-03-21) http://python.org/sf/1455676 closed by rhettinger floor division (2006-03-25) http://python.org/sf/1458419 closed by nnorwitz Improved PySet C API (2006-03-25) http://python.org/sf/1458476 closed by gvanrossum Add docs for zlib.decompressobj.flush optional param (2006-03-27) http://python.org/sf/1459630 closed by gbrandl New / Reopened Bugs ___________________ xmlrpclib.py problem solved (2006-03-17) CLOSED http://python.org/sf/1452174 opened by varun bhansaly htmllib doesn't properly substitute entities (2006-03-17) http://python.org/sf/1452246 opened by Helmut Grohne broken string on mbcs (2006-03-18) CLOSED http://python.org/sf/1452697 opened by ocean-city Defining a class with __dict__ brakes attributes assignment (2006-03-11) CLOSED http://python.org/sf/1448042 reopened by gbrandl Unexpected module reloading (2006-03-18) CLOSED http://python.org/sf/1453145 opened by Ali Gholami Rudi try-except-finally in the tutorial (2006-03-19) CLOSED http://python.org/sf/1453570 opened by George Yoshida conditional expression documentation missing/incorrect (2006-03-19) CLOSED http://python.org/sf/1453579 opened by Alan makesetup fails to tolerate valid linker options (2006-03-20) http://python.org/sf/1454227 opened by Jeff Blaine test_parsedate_acceptable_to_time_functions+DST = :-( (2006-03-20) http://python.org/sf/1454285 opened by Anthony Baxter Explanation of pow() in lib (2006-03-20) CLOSED http://python.org/sf/1454855 opened by Christoph Zwerschke import email fails (2006-03-20) CLOSED http://python.org/sf/1454912 opened by Sjoerd Mullender Incompatible size for long (int) in Python Win and Linux? (2006-03-21) CLOSED http://python.org/sf/1455357 opened by Michael Yanowitz pyport.h freebsd inconsistent (2006-03-21) CLOSED http://python.org/sf/1455641 opened by Jim Jewett Simplify use of Queues with consumer threads (2006-03-21) CLOSED http://python.org/sf/1455676 opened by Raymond Hettinger dictobject.c:dictresize() vulnerability (2006-03-22) http://python.org/sf/1456209 opened by Armin Rigo Traceback error when compiling Regex (2006-03-22) http://python.org/sf/1456280 opened by Wolfgang Grafen sliceobject ssize_t (and index) not completed (2006-03-22) http://python.org/sf/1456470 opened by Jim Jewett PEP Links broken on new website (2006-03-22) CLOSED http://python.org/sf/1456609 opened by Grant Olson round not rounding correctly (2006-03-23) CLOSED http://python.org/sf/1456775 opened by Norbert Sebok Unifying pickle and cPickle exception class hierarchies (2006-03-23) http://python.org/sf/1457119 opened by Ori Peleg urllib.splithost parses incorrectly (2006-03-23) CLOSED http://python.org/sf/1457264 opened by Steve AttributeError in upload_file on interrupted connection (2006-03-23) http://python.org/sf/1457312 opened by Stefan Behnel floor division not documented (2006-03-23) CLOSED http://python.org/sf/1457358 opened by Christoph Zwerschke byext.py errors (2006-03-23) CLOSED http://python.org/sf/1457411 opened by Jeff Lowery regs attribute on regex objects not documented (2006-03-24) CLOSED http://python.org/sf/1457470 opened by Jeff Lowery Malloc error on MacOSX/imaplib (2006-03-24) http://python.org/sf/1457783 opened by Andreas Jung cgi.FormContentDict constructor should support parse options (2006-03-25) http://python.org/sf/1457823 opened by John Belmonte Log._log needs to be more forgiving... (2006-03-24) http://python.org/sf/1458017 opened by Skip Montanaro sys.maxint should be mentioned in explanation of int type (2006-03-25) CLOSED http://python.org/sf/1458220 opened by Christoph Zwerschke lambda with a parenthesized argument raises TypeError (2006-03-27) CLOSED http://python.org/sf/1458903 opened by Jeong-Min Lee -Q warn option is still not default in 2.4 (2006-03-26) CLOSED http://python.org/sf/1458927 opened by Christoph Zwerschke Doubled backslash in repr() method for unicode (2006-03-27) CLOSED http://python.org/sf/1459029 opened by Christoph Zwerschke missing links beetween strftime()'s... (2006-03-27) CLOSED http://python.org/sf/1459103 opened by Jens Diemer inspect.getargspec() is wrong for def foo((x)): (2006-03-27) http://python.org/sf/1459159 opened by Neal Norwitz sgmllib.SGMLparser and hexadecimal numeric character refs (2006-03-27) http://python.org/sf/1459279 opened by Francesco Ricciardi time.timezone / time.strftime('%z') problem (2006-03-27) CLOSED http://python.org/sf/1459642 opened by Simon Lanzmich sets.Set can't be subclassed (2006-03-28) CLOSED http://python.org/sf/1459733 opened by Michal Kwiatkowski test suite should pass with -Qnew ? (2006-03-28) CLOSED http://python.org/sf/1459808 opened by Anthony Baxter urllib2 changes header names (2006-03-28) CLOSED http://python.org/sf/1459963 opened by Michael Vert random.sample can raise KeyError (2006-03-29) http://python.org/sf/1460340 opened by paul rubin Bugs Closed ___________ make frameworkinstall fails on Intel Macs (2006-03-10) http://python.org/sf/1447607 closed by gbrandl xmlrpclib.py problem solved (2006-03-17) http://python.org/sf/1452174 deleted by gbrandl bug with xmlrpclib (2006-03-09) http://python.org/sf/1446690 closed by gbrandl asyncore dispatcher.__getattr__() masks self._map (2006-03-13) http://python.org/sf/1448639 closed by gbrandl svn head compiler fails to spot extended slicing (2006-03-02) http://python.org/sf/1441408 closed by ncoghlan (XMLRPC) multitude of sockets ending up in TIME_WAIT (2005-02-25) http://python.org/sf/1151968 closed by gbrandl README build instructions for fpectl (2004-01-07) http://python.org/sf/872175 closed by gbrandl Built-in compile function with PEP 0263 encoding bug (2005-02-03) http://python.org/sf/1115379 closed by nnorwitz broken string on mbcs (2006-03-18) http://python.org/sf/1452697 deleted by ocean-city Defining a class with __dict__ brakes attributes assignment (2006-03-11) http://python.org/sf/1448042 closed by gbrandl Python drops core when stdin is bogus (2005-11-10) http://python.org/sf/1353504 closed by gbrandl Inconsistency between StringIO and cStringIO (2006-01-27) http://python.org/sf/1416477 closed by gbrandl optparse docs double-dash confusion (2006-02-16) http://python.org/sf/1432838 closed by gbrandl Http redirection error in urllib2.py (2005-11-10) http://python.org/sf/1353433 closed by gbrandl Unexpected module reloading (2006-03-18) http://python.org/sf/1453145 closed by loewis try-except-finally in the tutorial (2006-03-19) http://python.org/sf/1453570 closed by gbrandl conditional expression documentation missing/incorrect (2006-03-19) http://python.org/sf/1453579 closed by gbrandl shelve/bsddb crash on db close (2005-06-26) http://python.org/sf/1227955 closed by nnorwitz Explanation of pow() in lib (2006-03-20) http://python.org/sf/1454855 closed by rhettinger import email fails (2006-03-20) http://python.org/sf/1454912 closed by bwarsaw Incompatible size for long (int) in Python Win and Linux? (2006-03-21) http://python.org/sf/1455357 closed by perky pyport.h freebsd inconsistent (2006-03-22) http://python.org/sf/1455641 closed by perky problems with too many sockets in FreeBSD (2006-03-11) http://python.org/sf/1448058 closed by nnorwitz PEP Links broken on new website (2006-03-23) http://python.org/sf/1456609 closed by gbrandl Pointer freed twice in Py_InitializeEx() (03/07/06) http://python.org/sf/1444893 closed by sf-robot Popen4 wait() fails sporadically with threads (2005-04-15) http://python.org/sf/1183780 closed by loewis Python 2.2.3 crashes using popen2 to spawn lots of children (2004-01-28) http://python.org/sf/886492 closed by nnorwitz round not rounding correctly (2006-03-23) http://python.org/sf/1456775 closed by gbrandl urllib.splithost parses incorrectly (2006-03-23) http://python.org/sf/1457264 closed by gbrandl floor division not documented (2006-03-23) http://python.org/sf/1457358 closed by nnorwitz byext.py errors (2006-03-23) http://python.org/sf/1457411 closed by nnorwitz regs attribute on regex objects not documented (2006-03-24) http://python.org/sf/1457470 closed by gbrandl build doesn't pick up bsddb w/Mandrake 9.2 (2004-09-23) http://python.org/sf/1033390 closed by nnorwitz sys.maxint should be mentioned in explanation of int type (2006-03-25) http://python.org/sf/1458220 closed by gbrandl lambda with a parenthesized argument raises TypeError (2006-03-26) http://python.org/sf/1458903 closed by nnorwitz -Q warn option is still not default in 2.4 (2006-03-26) http://python.org/sf/1458927 closed by gbrandl Doubled backslash in repr() method for unicode (2006-03-27) http://python.org/sf/1459029 closed by anthonybaxter missing links beetween strftime()'s... (2006-03-27) http://python.org/sf/1459103 closed by gbrandl time.timezone / time.strftime('%z') problem (2006-03-27) http://python.org/sf/1459642 closed by gbrandl sets.Set can't be subclassed (2006-03-28) http://python.org/sf/1459733 closed by gbrandl test suite should pass with -Qnew ? (2006-03-28) http://python.org/sf/1459808 closed by gbrandl urllib2 changes header names (2006-03-28) http://python.org/sf/1459963 closed by gbrandl New / Reopened RFE __________________ sys.setatomicexecution - for critical sections (2006-03-18) http://python.org/sf/1453341 opened by kxroberto addheaders for urlopen / open / xxxx_open (2006-03-19) http://python.org/sf/1453973 opened by kxroberto Make more out of 'as' : general ad-hoc right-assignment (2006-03-20) CLOSED http://python.org/sf/1454344 opened by kxroberto Python space syntax & pythonic long lambda's (2006-03-20) CLOSED http://python.org/sf/1454364 opened by kxroberto RFE Closed __________ Missing 4 socket object properties (2002-06-12) http://python.org/sf/567972 closed by gbrandl Constructor for counting things (2003-05-17) http://python.org/sf/739029 closed by gbrandl Make more out of 'as' : general ad-hoc right-assignment (2006-03-20) http://python.org/sf/1454344 closed by gbrandl Python space syntax & pythonic long lambda's (2006-03-20) http://python.org/sf/1454364 closed by gbrandl From skip at pobox.com Sat Mar 11 09:51:35 2006 From: skip at pobox.com (skip at pobox.com) Date: Sat, 11 Mar 2006 08:51:35 -0600 Subject: New python.org site In-Reply-To: <6a246d8e0603110637q13339803u2db266c3ed98a534@mail.gmail.com> References: <140mqj7t7y2s5$.r1fgnfqmwl29$.dlg@40tude.net> <6a246d8e0603110637q13339803u2db266c3ed98a534@mail.gmail.com> Message-ID: <17426.58359.193459.761265@montanaro.dyndns.org> Bertrand> 1. Who is maintaining python.org ? Start with mail to webmaster at python.org. Bertrand> 2. Where is the site code/design available ? It's in Subversion. Start here: http://psf.pollenation.net/ Bertrand> 3. Is the last redesign a solo or a community effort ? Small community. One person did the bulk of the work. A sprint at the recent PyCon a week ago finished many things off and got a lot of content converted from the old site to the new. Stuff that hasn't yet been converted and hasn't had proper redirects set up falls through to the old site (that is obvious when it happens). Hopefully the number of pages where that occurs is dropping. Now the developers are tackling a lot of bug reports, converting the last content and fixing redirect problems. The conversion has been particularly challenging because not only was the site redesigned from an appearance standpoint, it was restructured (almost all content got new URLs) and a new content management system was written to support the content (http://pyramid.pollenation.net/). Oh, the Subversion repository holding the content changed as well. Skip From kent at kentsjohnson.com Fri Mar 24 23:31:05 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 24 Mar 2006 23:31:05 -0500 Subject: don't understand popen2 In-Reply-To: References: <4421effd$0$11070$e4fe514c@news.xs4all.nl> <44225c55$0$11064$e4fe514c@news.xs4all.nl> <4422e21a_3@newspeer2.tds.net> Message-ID: <4424c268$1_3@newspeer2.tds.net> Sion Arrowsmith wrote: > Kent Johnson wrote: > >>Sion Arrowsmith wrote: >> >>>(and please avoid the abuse of raw strings for Windows paths). >> >>Why do you consider that abuse of raw strings? > > I consider it abuse because it's not what they were invented for. > I consider discouraging it to be a good thing in order to reduce > the chances of people being bitten by, for instance: > >>>>os.listdir(r"C:\") > > File "", line 1 > os.listdir(r"C:\") > ^ > SyntaxError: EOL while scanning single-quoted string > > and getting all confused on this group. Judging from the traffic here, people are far more often bitten by *not* using raw strings for paths containing \ than they are by using them for paths ending with \. So perhaps we should encourage raw strings for Windows paths. ;) Kent From fredrik at pythonware.com Mon Mar 6 07:19:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 6 Mar 2006 13:19:39 +0100 Subject: raw strings and \ References: <1141548565.145199.145910@e56g2000cwe.googlegroups.com> <1141576051.081203.318010@e56g2000cwe.googlegroups.com> <1141580826.470715.319020@i40g2000cwc.googlegroups.com> <65mdnffSMISumZHZRVnzvA@telenor.com> Message-ID: "Blackbird" wrote: > Slightly OT, but here is a crazy little program that shows the power of > using raw strings: > > s=r'print "s=r\'%s\'\n%s"%(s,s)' > print "s=r\'%s\'\n%s"%(s,s) > > When run, this program will print an exact copy of itself. I'm not sure what the raw strings brings to the table, though; it's not like you need them to write a "self-replicating" python program: http://miscoranda.com/37 From niemand.leermann at thomas-guettler.de Wed Mar 8 10:43:37 2006 From: niemand.leermann at thomas-guettler.de (Thomas Guettler) Date: Wed, 08 Mar 2006 16:43:37 +0100 Subject: cgi problem References: <7xk6b5mjpw.fsf_-_@ruckus.brouhaha.com> Message-ID: Am Wed, 08 Mar 2006 00:19:55 -0800 schrieb Paul Rubin: > I'm trying to write a simple cgi that reads a post from the user's > browser, does some stuff with the form data, and redirects the browser > back to the originating url, i.e. I want the cgi to send a 302 > redirect. Hi, I have this setup for a small script (for bigger things I use quixote) def cgi_main(): stdout=sys.stdout sys.stdout=sys.stderr # print soll zu Apache-Log try: html=cgi_html() except ReturnThis, r: stdout.write(str(r)) return stdout.write("Content-Type: text/html\n\n%s" % html) CGI-Script *very* small ........... # Python Imports import os import sys import cgitb cgitb.enable() import foo if __name__=="__main__": foo.cgi_main() ............ file foo: def cgi_main(): stdout=sys.stdout sys.stdout=sys.stderr # print should go to Apache-Log try: html=cgi_html() except ReturnThis, r: stdout.write(str(r)) return stdout.write("Content-Type: text/html\n\n%s" % html) class ReturnThis(Exception): pass class Redirect(ReturnThis): def __init__(self, destination): if os.environ.get("HTTPS")=="on": http="https://" else: http="http://" url="%s%s%s%s" % (http, os.environ["SERVER_NAME"], os.environ["SCRIPT_NAME"], destination) header="Status: 302 Moved Temporarily\nLocation: %s\n\n" % ( url) ReturnThis.__init__(self, header) Now you can 'raise Redirect("mylocation")' anywhere in your code. 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 simon at brunningonline.net Thu Mar 2 06:19:20 2006 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 2 Mar 2006 11:19:20 +0000 Subject: Newbie errors :-( Need help In-Reply-To: <20060302110145.73025.qmail@web34601.mail.mud.yahoo.com> References: <20060302110145.73025.qmail@web34601.mail.mud.yahoo.com> Message-ID: <8c7f10c60603020319m456ce316y9d7dac61a170ea36@mail.gmail.com> On 3/2/06, - C Saha - wrote: > I am getting the result but along with this error, any idea what could be > the reason? > > fibo.fib(1000) > 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987Traceback (most recent call > last): > File "", line 1, in ? > File "fibo.py", line 8, in fib > return result > NameError: global name 'result' is not defined > > Code is given below > # Fibonacci numbers module > def fib(n): # write Fibonacci series up to n > a, b = 0, 1 > while b < n: > print b, > a, b = b, a+b > return result You are returning something called 'result', but you never create anything with that name. Since in your function you are printing your results, you should be able to just drop that line and it'll work just fine. If OTOH you want your function to return something that can be used elsewhere, you might try something like (untested): def fib(n): a, b = 0, 1 result = list() while b < n: result.append(b) a, b = b, a+b return result (You might also do this with a generator - in fact that's not a bad idea - but generators are an advanced subject, so I'd steer clear for the moment) -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From tzot at sil-tec.gr Wed Mar 8 12:22:56 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Wed, 08 Mar 2006 19:22:56 +0200 Subject: Send email notification References: <1141759889.952367.59260@j33g2000cwa.googlegroups.com> <1141760916.715817.3800@i40g2000cwc.googlegroups.com> Message-ID: <724u02lh61ji388247603e1gfgdmfncarh@4ax.com> On Wed, 08 Mar 2006 06:20:42 +0000, rumours say that Steve Holden might have written: > If we >weren't paid thousands of dollars a week to answer questions on this >list we'd probably get snarky more often. Steve, please, don't make me look like a liar in front of the children! -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From onurb at xiludom.gro Tue Mar 14 08:37:39 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 14 Mar 2006 14:37:39 +0100 Subject: Accessing overridden __builtin__s? In-Reply-To: References: <1142311784.996095.158950@j33g2000cwa.googlegroups.com> Message-ID: <4416c756$0$9636$636a55ce@news.free.fr> Steven D'Aprano wrote: > On Mon, 13 Mar 2006 21:28:06 -0800, garyjefferson123 wrote: > > >>I'm having a scoping problem. I have a module called SpecialFile, >>which defines: >> (snip code) >>The problem, if it isn't obvioius, is that the open() call in __init__ >>no longer refers to the builtin open(), but to the module open(). > > > In your code, open() is not a module, it is a function. Steven, it seems clear that the OP knows that already. Try reading the previous sentence as: """ The problem, if it isn't obvioius, is that the open() call in __init__ no longer refers to the builtin's open(), but to the module's open(). """ Does it make more sens ?-) > A better technique will be to turn open into a method of the class > SpecialFile, rather than a bare function. That way you keep open() the > built-in function separate from SpecialFile.open(). > > >>So, if I do: >> >>f = SpecialFile.open(name, mode) >> >>I get infinite recursion. > > > I see you are already using an open method. There again, you may want to read more carefully: SpecialFile is *also* the module's name - which, I agree, is not pythonic. (snip) > > I would handle it like this: > > class SpecialFile(object): > def __init__(self, fname, mode='r'): > self.fname = fname > self.mode = mode > def open(self): > self.f = open(self.fname, self.mode) > def close(self): > self.f.close() > def read(self): > return self.f.read() > def write(self, data): > self.f.write(data) > > You use it like so: > > sf = SpecialFile("hello.txt") > sf.open() > data = sf.read() > sf.close() Small variant, more builtins-open-like, and taking full advantage of Python's delegation mechanism: class SpecialFile(object): def __init__(self, fname, mode='r'): self.fname = fname self.mode = mode self._file = open(self.fname, self.mode) def __getattr__(self, name): return getattr(self._file) which allows: sf = SpecialFile("hello.txt") # then use it just like any other file object 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 fredrik at pythonware.com Mon Mar 13 06:19:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Mar 2006 12:19:19 +0100 Subject: Anomalous behaviour when compiling regular expressions? References: <5959791F562E9E47B90254AECFD55B3B30D8A4@UKEXBE01.UK.CorpLAN.net> Message-ID: Fredrik Lundh wrote: > I have no time to sort out why your second example doesn't give the > same error oh, it was there it went. From onurb at xiludom.gro Fri Mar 3 08:59:18 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 03 Mar 2006 14:59:18 +0100 Subject: setattr question In-Reply-To: <1141382590.464384.29840@v46g2000cwv.googlegroups.com> References: <1141318090.569997.247760@z34g2000cwc.googlegroups.com> <4407355d$0$10756$636a55ce@news.free.fr> <1141335149.855403.261510@e56g2000cwe.googlegroups.com> <440803ba$0$15069$636a55ce@news.free.fr> <1141382590.464384.29840@v46g2000cwv.googlegroups.com> Message-ID: <44084be0$0$15822$636a55ce@news.free.fr> Gerard Flanagan wrote: > bruno at modulix wrote: > [...] > >>I don't know this HtmlElement class, nor where it comes from. >>'to_string()' (or is it toString() ?) is javaish. The pythonic idiom for >>this is implementing the __str__() method and calling str(obj) on the >>obj (which will call obj.__str__()). Hence my (bad) guess about you >>being a Javaer. >> > > > I've made this change, thanks. ( I had a year with C# so maybe that's > why I'm so idiomatically-challenged ! ) Well, C# being somewhat inspired by Java... > >>Not the HtmlElement class, but the HtmlBuilder one. Here again, a class >>defining only staticmethods is a pretty javaish idiom - in Python, we >>just use good old functions !-) (in a separate module if you want a >>separate namespace). >> > > But it's personal preference, no? Well, in Python, there are a lot of things that can be done the way you like it, but are better done the idiomatic way. Python relies quite a lot on conventions and idioms where other languages try to inforce strict rules. > The functions were kind of related > and meaningless outside the module they were declared - FWIW (and from the snippet I saw), these functions are useless even in the module !-) Unless you want to dynamically choose the concrete class at runtime based on platform/settings/phase of the moon/whatnot (which seems not to be te case in the snippet you posted), you don't need these functions, just instanciating the concrete class is enough. Remember that Python classes *are* factory already - and that you can freely replace a class by any callable returning an instance, ie: == before refactoring, directly instanciating concrete class == # myhtmlmodule.py class HtmlElement(tag, *args, **kw): # code here # myclientmodule.py from myhtmlmodule import HtmlElement ul = HtmlElement('ul') == after refactoring, using a factory function == # myhtmlmodule.py class _HtmlElement1(tag, *args, **kw): # code here class _HtmlElement2(tag, *args, **kw): # other code here # yes, it's now a function... def HtmlElement(tag, *args, **kw): if phase_of_the_moon(): klass = _HtmlElement1 else: klass = _HtmlElement2 return klass(tag, *args, **kw) # myclientmodule.py # well... nothing changed here !-) from myhtmlmodule import HtmlElement ul = HtmlElement('ul') You could also do the trick with metaclass black magic, but what, KISS... > but I'll take > it on board, anyway. > > [...] > > >>My experience is that it's far easier to start simple and add >>flexibility where needed than to simplify useless complexity. KISS, >>yagni and all that kind of things... >> > > yagni - I'd never heard that one! You Aint Gonna Need It. Code not written is the best code, so don't write code "just in case". Python is usually dynamic enough to make refactoring easy (cf example above) > I've ditched the factory class in any case: > > http://gflanagan.net/site/python/htmlbuilder/HtmlBuilder.py > (FWIW) Seems mostly clean. May I suggest a couple small corrections/improvements ? 1/ potential bugfix: try: from tidy import parseString except ImportError: def parseString(text): # woops, this function is supposed to return something #pass return text 2/ safer and cleaner class HtmlPage(HtmlElement): # removed class vars, # replaced with default in __init__ def __init__(self, title, **kw): self.title = title self.stylesheets = kw.get('stylesheets', []) self.doctype = kw.get('doctype', HTML4_STRICT) >>BTW, there's also a french speaking python newsgroup at fr.comp.lang.py. > > I wasn't aware of that, I'll have a lurk! see you there !-) >>-- >>bruno desthuilliers >>python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for >>p in 'onurb at xiludom.gro'.split('@')])" > > -- 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 Thu Mar 2 09:52:45 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 02 Mar 2006 15:52:45 +0100 Subject: filename variables References: <1141310725.841335.173340@i40g2000cwc.googlegroups.com> Message-ID: <46of70Fc28saU1@uni-berlin.de> cyborg4 at walla.co.il wrote: > If in Windows XP I use: > > openstring= "test.py >foo.txt" > os.system(openstring) > > it works. > > > But if I use: > > file1='foo.txt' > openstring= "test.py >"+file1 > > It gives an IOError about no such file or directory as > \\mydidr\\foo.txt > > What does it mean ? That you obviously didn't give us the actual (non-) working code, but something you believe is essential. Because file1='foo.txt' openstring= "test.py >"+file1 certainly doesn't give that error. Post a running, self contained examplpe, and we might be able to help you. Diez From ram0812 at hotmail.com Thu Mar 23 15:00:59 2006 From: ram0812 at hotmail.com (Raja Raman Sundararajan) Date: 23 Mar 2006 12:00:59 -0800 Subject: MS word document generator In-Reply-To: <1142515766.267572.208430@i40g2000cwc.googlegroups.com> References: <1142413907.226088.190740@j33g2000cwa.googlegroups.com> <441873b2$0$1337$8fcfb975@news.wanadoo.fr> <1142455729.303313.34210@j52g2000cwj.googlegroups.com> <1142515766.267572.208430@i40g2000cwc.googlegroups.com> Message-ID: <1143144058.998409.166260@v46g2000cwv.googlegroups.com> Hi paron, I am using PyRTF as of now and it seems to fit my need quite well and it works like a charm :-). I have made a wrapper around it so that it will easier for me to switch the backend for generating the word/RTF docs later. May be, it will be openoffice :-) I appreciate your input. Thank you. :-) From sto'niets'11 at telenet.'nothing'.be Wed Mar 15 17:08:40 2006 From: sto'niets'11 at telenet.'nothing'.be (Rc) Date: Wed, 15 Mar 2006 22:08:40 GMT Subject: Python compiler Message-ID: Hello everybody I'm a newbie, fromBelgium. My question is where can I find a compiler for free. For Windows XP. Thanks Roger Sorry for my English From jrivero at python.org.ve Mon Mar 27 15:57:49 2006 From: jrivero at python.org.ve (Jesus Rivero - (Neurogeek)) Date: Mon, 27 Mar 2006 16:57:49 -0400 Subject: Where does Python look for libraries? In-Reply-To: References: Message-ID: <442851CD.8070604@python.org.ve> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Python has sys.path If you want to add dirs into your PYTHONPATH add them to sys.path Jesus Rivero - (Neurogeek) ACB wrote: > I have been trying to get the gdmodule installed and have run into > an issue. When I import gd I get the following error. > >>>> import gd > > Traceback (most recent call last): File "", line 1, in ? > File "/usr/local/lib/python2.3/site-packages/gd.py", line 10, in ? > import _gd ImportError: /usr/local/lib/libgd.so.2: Undefined symbol > "libiconv_open" > > But, when I run nm libiconv.so in the directory with the iconv > library I get an entry like this 00011fe0 T libiconv_open > > so I know the functionality is there. So, my question. Does > python have a way to add search directories for locating libraries? > > > Thanks. > > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFEKFHNdIssYB9vBoMRAli3AJ9dFHXpXnrKCWiiSZZhuedKvZnQXgCeLeQF QbRIUt2RC//D+RMrWFsg8lY= =S8Ke -----END PGP SIGNATURE----- From __peter__ at web.de Mon Mar 20 07:59:21 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 20 Mar 2006 13:59:21 +0100 Subject: String comparison question References: <400BDC416E2A0042AA35DF3919BB8A5115E648@mail.mtl.proksim.com> <1142858790.888174.143470@i40g2000cwc.googlegroups.com> Message-ID: luc.saffre at gmail.com wrote: > Michael Spencer wrote: >> Olivier Langlois wrote: >> >> > I would like to make a string comparison that would return true without >> > regards of the number of spaces and new lines chars between the words >> > >> > like 'A B\nC' = 'A\nB C' > > Here is how I do such comparisons: > > if a.strip().split() == b.strip().split() The strip() is not necessary: >>> " a b c\n ".split() == "a b c".split() True Peter From bradford653 at gmail.com Wed Mar 8 11:28:23 2006 From: bradford653 at gmail.com (Tom Bradford) Date: 8 Mar 2006 08:28:23 -0800 Subject: Type Hinting vs Type Checking and Preconditions In-Reply-To: References: Message-ID: <1141835303.880207.18640@j52g2000cwj.googlegroups.com> This type of hinting would only break type ducking in-so-much as a function that leveraged that hinting would be looking specifically for an instance of a particular type, which would be absolutely no different than a developer performing the type check manually and throwing it out if the type were invalid. It would otherwise just be a lot of tedious and repetitive work for the developer. The fact is, as valuable as type ducking is, it has drawbacks in its ambiguousness, that are especially harmful to large systems that are being developed with many hands in the pot. And no, people who use a library that leverages this type of hinting are most certainly no more effected by it than they would be by the methods performing the check manually. As the feature is optional, if you want to allow a method that allows for type ducking, you would write it in exactly the same way you write it now, and nobody would be harmed in the process. From sjmachin at lexicon.net Mon Mar 20 05:39:25 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 20 Mar 2006 21:39:25 +1100 Subject: ANNOUNCE: xlrd 0.5.2 -- extract data from Excel spreadsheets In-Reply-To: <1142850490.058912.138560@e56g2000cwe.googlegroups.com> References: <441c7714$1_2@newspeer2.tds.net> <441C9F4D.1030203@lexicon.net> <441ccb61$1_3@newspeer2.tds.net> <441D23F2.7090808@lexicon.net> <1142850490.058912.138560@e56g2000cwe.googlegroups.com> Message-ID: <441E865D.20508@lexicon.net> On 20/03/2006 9:28 PM, jcmendez wrote: > John > > Thanks for walking us through the comparison. On the xlrd website I > saw that it does not import formulas from the Excel files, which is > what I'm looking for. Any suggestions? > > Juan C. > Juan, what do you want to do with the formulas after importing them? Pretty-print them? Evaluate them? Cheers, John From boyee118 at gmail.com Thu Mar 30 04:04:48 2006 From: boyee118 at gmail.com (boyeestudio) Date: Thu, 30 Mar 2006 01:04:48 -0800 Subject: How to run python program on the embeded system? Message-ID: How to run python program on the embeded system? My mobile phone support J2ME,CLDC-1.1,midp-2.0 and I want to let it run python program,but I have no idea how to..... Maybe I need write a python compiler which can run on my phone,But it is a complex work. Please help and tell me What can I do....,Thanks a lot!!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjl at pobox.com Thu Mar 23 14:53:16 2006 From: jjl at pobox.com (John J. Lee) Date: 23 Mar 2006 19:53:16 +0000 Subject: python-announce moderation (was: Re: ANN: ClientForm 0.2.2 released) References: Message-ID: <87wtelndjn.fsf@pobox.com> aahz at pythoncraft.com (Aahz) writes: > In article , > John J Lee wrote: > > > >Hmm, hschilling at nasa.gov, who are you? python-announce moderator? I > >didn't put you on my To: line (nor python-list for that matter, but I > >guess that's a reasonable place for it to go...). > > > >Also FYI, it ended up going to wwwsearch-general twice, I guess because > >the you (or the moderation software) forwarded it there after moderation, > >which isn't really necessary. > > Huh??? Sorry. I forgot my reply wouldn't include the headers (should have hit 'forward' instead of 'reply'. I sent the message I quoted "To: python-announce at python.org, wwwsearch-general at lists.sourceforge.net". It arrived at the latter list. A while later, it got moderated for python-announce, and was sent out like so: Date: Thu, 23 Mar 2006 18:25:57 +0000 (GMT Standard Time) From: John J Lee To: hschilling at nasa.gov Cc: wwwsearch-general at lists.sourceforge.net, python-list at python.org Subject: [wwwsearch-general] python-announce moderation (was: Re: ANN: ClientForm 0.2.2 released) I wondered where that To: line came from (I don't even know who hschilling at nasa.gov is), and why it was sent to wwwsearch-general again (there was no need, since my original To: line already got it to that list). No real harm done, but I'm curious and thought something needed fixing. John From sybrenUSE at YOURthirdtower.com.imagination Sat Mar 11 15:25:07 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sat, 11 Mar 2006 21:25:07 +0100 Subject: Help Create Good Data Model References: <1142107183.358685.266440@i39g2000cwa.googlegroups.com> Message-ID: mwt enlightened us with: > I'm reworking a little app I wrote, in order to separate the data > from the UI. Good idea. > As a start, I wanted to create a iron-clad data recepticle that will > hold all the important values, and stand up to being queried by > various sources, perhaps concurrently. Why do that yourself, if you can have SQLite databases? SQLite is even capable of in-memory databases. No need to re-invent the wheel. 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 Fri Mar 31 11:20:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 31 Mar 2006 18:20:08 +0200 Subject: member variables in python References: <1143819190.360242.314830@z34g2000cwc.googlegroups.com> Message-ID: "PyPK" wrote: > hi how do I write this better with member variables rather than global > as you see below. > > eg: > > test-flag = 0 > > class AA: > def __init__(...): > > def methos(self,...): > global test-flag > test-flag = xx > > instead of something like above ..how do i put it i terms of member > variables? you mean something like class AA: def __init__(self): self.test_flag = 0 # initialize def methods(self, value): self.test_flag = value # ... aa = AA() aa.methods(1) print aa.test_flag ? From mtobis at gmail.com Fri Mar 24 15:39:05 2006 From: mtobis at gmail.com (Michael Tobis) Date: 24 Mar 2006 12:39:05 -0800 Subject: a problem to solve In-Reply-To: References: <5oiUf.1818$No6.41433@news.tufts.edu> <1143071664.377833.136660@z34g2000cwc.googlegroups.com> Message-ID: <1143232745.363162.53810@j33g2000cwa.googlegroups.com> First do a little estimation. We know we have to find four out of 16 switches, so the number of possibilities to search is only C(4,16) = 1820, so an exhaustive search will work. These will turn on 15 lights in each set of 20, of which the number of possibilities is C(15,20)**4 = 57779667567968256L The number of these that are successes is the number of ways to pick 3 out of 4 twenty times: 4**20 = 1099511627776L For each pick, your chance of success is then float(1099511627776L)/57779667567968256L = 1.9029386530869287e-05 You get 1820 distinct tries. Assuming no overlap (which slightly overestimates your chances if it's a false assumption), the odds that there is a solution are 1820 * 1.9029386530869287e-05 = 0.034633483486182101 or about 3.5%. Not great. There seem to be some symmetries I haven't used, which may conceivably help your cause. I just wonder if you have some basis for beleiving that there is a solution. mt From tzot at sil-tec.gr Sat Mar 18 07:51:38 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Sat, 18 Mar 2006 14:51:38 +0200 Subject: File Permissions References: <1142000418.480825.247970@v46g2000cwv.googlegroups.com> Message-ID: On Fri, 10 Mar 2006 16:43:15 +0200, rumours say that Juho Schultz might have written: >VJ wrote: >> Hi All >> >> Basically i want to write into a file .If the permissions are not there >> then print a error message. >> How do i achive this ??? >> >> Thanks, >> VJ >One way would be a try-except block, and leave the permission checking >error message generation, etc. to the operating system. > >try: > outfile = file(outfilename,"w") >except IOError, errormsg > print "Could not write to file %s: %s" % (outfilename, errormsg) As a word of caution: the OP is checking for the permissions of an *existing* file. Both Juho's and Sybren's suggestions *destroy* the file's contents. So, VJ, I'd suggest the following change: Open the file for read write outfile= open(outfilename, "r+b") # I assume binary and later on catch errors in .write operations. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From amaltasb at gmail.com Thu Mar 30 01:57:59 2006 From: amaltasb at gmail.com (amaltasb at gmail.com) Date: 29 Mar 2006 22:57:59 -0800 Subject: difference between .cgi and .py Message-ID: <1143701879.632741.6220@g10g2000cwb.googlegroups.com> Hi, I am new to python.. I have uploaded few scripts in my cgi-bin folder, some with extension .cgi and some with .py. What is the difference between the two extensions.. which one is more prefered, do it effects performance ?? Thanks From the.theorist at gmail.com Wed Mar 15 11:20:53 2006 From: the.theorist at gmail.com (the.theorist) Date: 15 Mar 2006 08:20:53 -0800 Subject: stdin or optional fileinput Message-ID: <1142439653.706305.134290@j33g2000cwa.googlegroups.com> I was writing a small script the other day with the following CLI prog [options] [file]* I've used getopt to parse out the possible options, so we'll ignore that part, and assume for the rest of the discussion that args is a list of file names (if any provided). I used this bit of code to detect wether i want stdinput or not. if len(args)==0: args = [ sys.stdin ] Now in my main loop I've written: for file in args: for line in open( file ): #do stuff The probelm occurs when I pass no arguments and python trys to open( sys.stdin ). open() customarily accepts a pathname, and returns a file object. But this code is so elegant I thought that maybe, if open were passed file object it could re-open that file in a new mode (if a mode was provided different from the current mode) or simply return the file object it was passed. Anyhow, what do you guys think? There might be something about my idea that makes this proposed behavior of open() unexpected, and I just haven't thought of it. From python at hope.cz Sat Mar 18 08:12:46 2006 From: python at hope.cz (Lad) Date: 18 Mar 2006 05:12:46 -0800 Subject: How to convert Message-ID: <1142687566.540612.83480@z34g2000cwc.googlegroups.com> How can I covert in Python a variable of a long type to variable of Integer type? Thank you for reply L. From grante at visi.com Tue Mar 7 12:11:33 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 07 Mar 2006 17:11:33 -0000 Subject: Pyserial again References: <1141661808.753184.157150@e56g2000cwe.googlegroups.com> <1141665448.418740.167910@i40g2000cwc.googlegroups.com> <120ossf55scsj8b@corp.supernews.com> <1141675566.162480.148260@v46g2000cwv.googlegroups.com> <1141681967.017912.180250@j33g2000cwa.googlegroups.com> <1141721704.444044.212620@p10g2000cwp.googlegroups.com> <120r82c3co02d94@corp.supernews.com> <120r9svhr2bbh6f@corp.supernews.com> <1141747058.800466.121010@j52g2000cwj.googlegroups.com> <1141748811.548153.265880@j33g2000cwa.googlegroups.com> Message-ID: <120rfm55ufhla0a@corp.supernews.com> On 2006-03-07, luca72 wrote: > Ok you write that it close :Because the "ser" object is never > used after that point, so it get's garbage collected and > deleted. Yes. > But for example if i make one button with the same caracteristic of the > previous com port: > > def OnButton1Button(self, event): > > ser = serial.Serial(0) > >> ser.baudrate = 9600 >> ser.parity = serial.PARITY_ODD >> ser.stopbits = serial.STOPBITS_TWO >> ser.bytesize =serial.EIGHTBITS >> ser.setRTS(level = 0) >> ser.setDTR(level = 0) >> ser.timeout = 1 > But with > a = textCtrl1GetValue() # i put here some different string > to send > ser.write (a) > b = ser.readline() > textCtrl2SetValue(b) I have no idea what you mean by that. POST THE CODE. With both button handlers. I'm GUESSING (since you won't post enough code for me to actually figure it otu) that "ser" is local to your button handlers and it's going out of scope and getting deleted when the button handler returns. Do you understand what I wrote above? > why at any read the serial close, is possible to prevent the > closure of the port? Yes. Make sure the "ser" object doesn't get deleted. -- Grant Edwards grante Yow! A can of ASPARAGUS, at 73 pigeons, some LIVE ammo, visi.com and a FROZEN DAQUIRI!! From just at xs4all.nl Fri Mar 3 05:38:47 2006 From: just at xs4all.nl (Just) Date: Fri, 03 Mar 2006 11:38:47 +0100 Subject: getting the reference count of an object ... References: Message-ID: In article , Wildemar Wildenburger wrote: > ... how? > > I'm writing an app that holds a public data dictionary from which other > objects obtain part of their __dict__ values so they all work on the > same dataset (yes I'm fiendishly clever and a constructor of unreadable > sentences (and code) ;)). > > My problem is that I haven't found an easy way to determine if said > dictionary contents are still in use (so it is ok to delete them from > the dictionary). I've thought about creating a dict subclass that counts > the number of assignments and deletions but that seems cumbersome (an > bug-prone). > > Is there a way to get the reference count of these datadict items? I > imagine that this would be a more stable implementation of such a feature. > > Hope this gets my problem accross; if not just bash me and I'll > reformulate. I'm not the best of explainers. > > Oh, and sorry if the solution to my problem is obvious (such as an > __refcount__ attribute or some stupid oversight like that). Direct answer: sys.getrefcount() Better answer: look at the weakref module, especially at the various Dict helper classes. Just From aahz at pythoncraft.com Thu Mar 23 14:25:20 2006 From: aahz at pythoncraft.com (Aahz) Date: 23 Mar 2006 11:25:20 -0800 Subject: python-announce moderation (was: Re: ANN: ClientForm 0.2.2 released) References: Message-ID: In article , John J Lee wrote: > >Hmm, hschilling at nasa.gov, who are you? python-announce moderator? I >didn't put you on my To: line (nor python-list for that matter, but I >guess that's a reasonable place for it to go...). > >Also FYI, it ended up going to wwwsearch-general twice, I guess because >the you (or the moderation software) forwarded it there after moderation, >which isn't really necessary. Huh??? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From johnjsal at NOSPAMgmail.com Mon Mar 20 14:43:07 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 20 Mar 2006 19:43:07 GMT Subject: what's the general way of separating classes? In-Reply-To: <441f02c5$0$29624$636a55ce@news.free.fr> References: <441f02c5$0$29624$636a55ce@news.free.fr> Message-ID: bruno at modulix wrote: >> It seems like this can >> get out of hand, since modules are separate from one another and not >> compiled together. You'd end up with a lot of import statements. > > Sorry, but I don't see the correlation between compilation and import > here ? I meant that in a language like C#, which compiles all the separate files into one program, it is not necessary to have the equivalent of an import/include type of statement. You can just refer to the classes from any other file. But in Python, without this behavior, you must explicitly import any external files. At least, I think I have that correct in my head. :) From goofyheadedpunk at gmail.com Wed Mar 8 21:46:32 2006 From: goofyheadedpunk at gmail.com (Brian L. Troutwine) Date: 8 Mar 2006 18:46:32 -0800 Subject: grayscale pixel based graphics with pygame Message-ID: <1141872392.131004.247580@v46g2000cwv.googlegroups.com> I've recently begun to teach myself pygame by making a bunch of small toys. My current toy is cellular automata displayer and I've gotten a bit stuck on the displaying bit. (If automata isn't the plural of automaton please forgive me.) The current automata are only binary and are calculated using 2D Numeric arrays. It had been my assumption that once the automata was calculated I could then multiply the entire array by 255 to get a nice array of grayscale pixel values. I had also hoped to feed the new grayscale array straight into surfarray as the manual talks in many places about 2Dpixel arrays taking integer pixel values. But I find the tutorials and manuals confusing and usually end up with black and blue displays. Could someone provide an explanation, and maybe a code example, as to how to create grayscale pixel based graphics with pygame using only 2D arrays? From mwql.aus at gmail.com Mon Mar 27 08:28:39 2006 From: mwql.aus at gmail.com (mwql) Date: 27 Mar 2006 05:28:39 -0800 Subject: Difference between 'is' and '==' In-Reply-To: <1143462121.828462.34290@v46g2000cwv.googlegroups.com> References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <1143462121.828462.34290@v46g2000cwv.googlegroups.com> Message-ID: <1143466119.249145.36960@i39g2000cwa.googlegroups.com> It's really strange, if a = 1 b = 1 a is b ==> True the same thing applies for strings, but not for dict, lists or tuples I think the 'is' operator is useful for objects only, not for primitive types, I think I solved the mystery behind my bugged code =) From skullw at sina.com.cn Sun Mar 12 05:23:58 2006 From: skullw at sina.com.cn (Skull) Date: Sun, 12 Mar 2006 18:23:58 +0800 Subject: Is the standard output thread-safe? References: Message-ID: Fernando Rodr?guez writes: > Hi, > > Is the standard output thread-safe? Can I use print from several > threads without having to use a mutex? > > Thanks > > Check this: http://me.in-berlin.de/doc/python/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe from my experience, it seems 'print' is not thread-safe. especially when it is called with formated string, such as: print "id:%d", my_id I think it is not an "atomic" operation. -- From brian at sweetapp.com Fri Mar 31 07:57:49 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 31 Mar 2006 14:57:49 +0200 Subject: Working with files in a SimpleXMLRPCServver In-Reply-To: References: Message-ID: <442D274D.20601@sweetapp.com> Jose Carlos Balderas Alberico wrote: > I'm setting up a server accepting XML-RPC calls using the > SimpleXMLRPCServer class. Basically, what I have to do is send a > zip-compressed file to the server, have the server unzip it and process > it, after processing it the server is supposed to zip the file again, > and send it back to the client. Using an XML-RPC server is overkill if you are just sending a single file and processing the result. You could just use a HTTP server. And Python has a library for doing zip processing (zlib), so you don't need to bother creating a file just to unzip your data. Cheers, Brian From bearophileHUGS at lycos.com Tue Mar 7 16:44:28 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 7 Mar 2006 13:44:28 -0800 Subject: Type Hinting vs Type Checking and Preconditions In-Reply-To: <1141764243.936880.324240@i39g2000cwa.googlegroups.com> References: <1141764243.936880.324240@i39g2000cwa.googlegroups.com> Message-ID: <1141767868.857660.262960@i39g2000cwa.googlegroups.com> You can look at this, its API looks very well thought out to me: http://oakwinter.com/code/typecheck/ > Now, on the other hand, if we were to introduce a purely optional type > hint to the function prototype, such as follows: > def multiplyByTwo(value:int): return value * 2 I don't think Python will have something like this... Bye, bearophile From deets at nospam.web.de Wed Mar 22 09:31:09 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 22 Mar 2006 15:31:09 +0100 Subject: struct size confusion: References: Message-ID: <48d5erFjneouU1@uni-berlin.de> Michael Yanowitz wrote: > Why is it 8 bytes in the third case and why would it be only 6 bytes > in the last case if it is 8 in the previous? >From TFM: """ Native size and alignment are determined using the C compiler's sizeof expression. This is always combined with native byte order. Standard size and alignment are as follows: no alignment is required for any type (so you have to use pad bytes); short is 2 bytes; int and long are 4 bytes; long long (__int64 on Windows) is 8 bytes; float and double are 32-bit and 64-bit IEEE floating point numbers, respectively """ See this how to achieve the desired results (on my system at least): >>> print struct.calcsize("I") 4 >>> print struct.calcsize("H") 2 >>> print struct.calcsize("HI") 8 >>> print struct.calcsize("=HI") 6 >>> print struct.calcsize("=IH") 6 >>> Regards, Diez From generic_user25 at yahoo.com Sun Mar 12 18:50:09 2006 From: generic_user25 at yahoo.com (Tito) Date: 12 Mar 2006 15:50:09 -0800 Subject: Can't simultaneously read/write from ossaudio dsp device Message-ID: <1142207409.510361.190890@i39g2000cwa.googlegroups.com> For an internet telephone application, I need to be able to read and write data to and from /dev/dsp simultaneously. I wrote some code and its not working. Anyone have any working code to do this? I am assuming my card is full duplex, it is a built-in sound card on a new dell 600m laptop, but I am not sure how to tell for sure. But I think the problem is not so much my sound card, but that I am making some fundamentally wrong assumption on the way to do this ;) Also I am definitely a newbie when it comes to audio coding, so any corrections or tips are welcome. Here is some test code that is failing for me -------------------------------------------------------- from twisted.internet.task import LoopingCall from twisted.internet import reactor import os, sys, wave, audioop """ While playing the contents of test1.wav, talk into the mic and have the audio recorded into /tmp/out.wav """ def playnlisten_out(): audio = wavin.readframes(1024) stereoaudio = audioop.tostereo(audio, 2, 1, 1) dsp.write(stereoaudio) def playnlisten_in(): audio = dsp.read(640) wavout.write(audio) def both(): playnlisten_out() playnlisten_in() dsp = ossaudiodev.open('/dev/dsp', 'rw') wavin = wave.open("test1.wav", "r") wavout = wave.open("/tmp/out.wav", "w") both_loop = LoopingCall(both) both_loop.start(0.02) reactor.run() ------------ Actual behavior ------------------------ It fails with an error: dsp.write(stereoaudio) exceptions.IOError: [Errno 19] No such device If I comment either playnlisten_out() or playnlisten_in() then the other function will work. They just don't work at the same time. ------------ Sys info ------------------------ box:~# lsmod | grep -i audio i810_audio 30356 1 ac97_codec 16908 1 i810_audio soundcore 9824 3 snd,i810_audio box:~# lsmod | grep -i snd snd_pcm_oss 48168 0 snd_mixer_oss 16640 1 snd_pcm_oss snd_intel8x0m 18632 0 snd_intel8x0 33068 0 snd_ac97_codec 59268 2 snd_intel8x0m,snd_intel8x0 snd_pcm 85412 3 snd_pcm_oss,snd_intel8x0m,snd_intel8x0 snd_timer 23172 1 snd_pcm snd_page_alloc 11144 3 snd_intel8x0m,snd_intel8x0,snd_pcm gameport 4736 1 snd_intel8x0 snd_mpu401_uart 7296 1 snd_intel8x0 snd_rawmidi 23232 1 snd_mpu401_uart snd_seq_device 7944 1 snd_rawmidi snd 50148 10 snd_pcm_oss,snd_mixer_oss,snd_intel8x0m,snd_intel8x0,snd_ac97_codec,snd_pcm,snd_timer,snd_mpu401_uart,snd_rawmidi,snd_seq_device soundcore 9824 3 snd,i810_audio box:~# lspci 0000:00:1f.5 Multimedia audio controller: Intel Corp. 82801DB/DBL/DBM (ICH4/ICH4-L/ICH4-M) AC'97 Audio Controller (rev 01) box:~# uname -a Linux box 2.6.7-1-386 #1 Thu Jul 8 05:08:04 EDT 2004 i686 GNU/Linux From michaeltaft at gmail.com Wed Mar 1 11:08:20 2006 From: michaeltaft at gmail.com (mwt) Date: 1 Mar 2006 08:08:20 -0800 Subject: Default Section Values in ConfigParser In-Reply-To: References: <1141175132.554532.123560@t39g2000cwt.googlegroups.com> Message-ID: <1141229300.563740.271270@i39g2000cwa.googlegroups.com> Thanks, Terry. That's an interesting way to go about it. From felipe.lessa at gmail.com Tue Mar 28 21:21:07 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 28 Mar 2006 23:21:07 -0300 Subject: sending ctrl C to a process In-Reply-To: <1143598491.283734.37180@t31g2000cwb.googlegroups.com> References: <1143598491.283734.37180@t31g2000cwb.googlegroups.com> Message-ID: <1143598867.3949.19.camel@kenshin> Em Ter, 2006-03-28 ?s 18:14 -0800, s99999999s2003 at yahoo.com escreveu: > It will need a Ctrl-C in order to break out of the program. > I wish to run this program using python (either thru os.system() or > some other subprocess modules) and how can i pass Ctrl-C to this > program to terminate it in python? $ python2.4 && echo " **** Python terminates!" Python 2.4.2 (#2, Mar 27 2006, 21:07:39) [GCC 4.0.3 (Debian 4.0.3-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ^C KeyboardInterrupt >>> try: ... while 1: ... pass ... except KeyboardInterrupt: ... print "\nHey, why did you press Ctrl-C?!" ... except: ... print "\nStrange..." ... ^C Hey, why did you press Ctrl-C?! >>> import sys >>> try: ... while 1: ... pass ... except KeyboardInterrupt: ... sys.exit(0) ... ^C **** Python terminates! $ HTH, -- Felipe. From davidh at ilm.com Fri Mar 24 13:47:19 2006 From: davidh at ilm.com (David Hirschfield) Date: Fri, 24 Mar 2006 10:47:19 -0800 Subject: Help: Creating condensed expressions Message-ID: <44243EB7.90506@ilm.com> Here's the problem: Given a list of item names like: apple1 apple2 apple3_SD formA formB formC kla_MM kla_MB kca_MM which is a subset of a much larger list of items, is there an efficient algorithm to create condensed forms that match those items, and only those items? Such as: apple[12] apple3_SD form[ABC] kla_M[MB] kca_MM The condensed expression syntax only has [...] and * as operators. [...] matches a set of individual characters, * matches any string. I'd be satisfied with a solution that only uses the [...] syntax, since I don't think it's possible to use * without potentially matching items not explicitly in the given list. I'm not sure what this condensed expression syntax is called (looks a bit like shell name expansion syntax), and I'm not even sure there is an efficient way to do what I'm asking. Any ideas would be appreciated. Thanks, -David -- Presenting: mediocre nebula. From ajsiegel at optonline.com Wed Mar 8 15:19:17 2006 From: ajsiegel at optonline.com (ajsiegel at optonline.com) Date: 8 Mar 2006 12:19:17 -0800 Subject: deriving from complex References: <440e2162$1@nntp0.pdx.net> <440e2554@nntp0.pdx.net> Message-ID: <1141849157.631367.201130@j33g2000cwa.googlegroups.com> Sch?le Daniel wrote: > thank you > I will have to take a closer look on __new__ > > Regards, Daniel The pypy implementation of the complex builtin may give you some clues. I found it helpful. http://codespeak.net/svn/pypy/dist/pypy/lib/cmath.py Art From scott.daniels at acm.org Mon Mar 6 14:10:26 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 06 Mar 2006 11:10:26 -0800 Subject: copying a tuple to a list.. In-Reply-To: <1141666930.931617.58180@j52g2000cwj.googlegroups.com> References: <1141666930.931617.58180@j52g2000cwj.googlegroups.com> Message-ID: <440c8732$1@nntp0.pdx.net> sergio at village-buzz.com wrote: > i have a result tuple from a MySQLdb call that would like to change in > place.. What you probably want: source = (1, 2, 'three') wanted = list(source) --Scott David Daniels scott.daniels at acm.org From grflanagan at yahoo.co.uk Thu Mar 9 05:43:53 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 9 Mar 2006 02:43:53 -0800 Subject: Python Evangelism References: Message-ID: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> Steve Holden wrote: > I've been thinking (and blogging) about python evangelism since PyCon, > as a result of which I created a squidoo lens: > > http://www.squidoo.com/pythonlogy > > Imagine my surprise at discovering that this has gone up in rank (by > number of views) from # 442,000 or so to #153! Clearly there's some > mileage in marketing Python, and I'd like to keep the buzz going if it > means more people will adopt the language. > > Any suggestions for improvement? > '-nology' not '-nlogy' in the link. I like the 'What's Happening on Planet Python' section - I find the planetpython.org gives too much of an intro to the pages it links to. A line or too, as in the lens site, would be preferable in my view. Just a thought - would a similar section be suitable for 'python.org' main page? Gerard From rajesh1986 at gmail.com Sat Mar 4 00:49:57 2006 From: rajesh1986 at gmail.com (Rajesh Sathyamoorthy) Date: Sat, 4 Mar 2006 13:49:57 +0800 Subject: Calculating md5 checksums. Message-ID: <47a726d60603032149s3f0de7e6r14197fabc4d40052@mail.gmail.com> I tried the script and had to get a hexdigest to get the value provided My test: SimplyMEPIS-3.3.1-1.iso checksum: 41a19060d3bb37bd596708ba77964491 i got: 41a19060d3bb37bd596708ba77964491 Do people normally provide md5 checksum in a *hexadecimal string? *Besides that, is the script reliable? Replies: Rajesh Sathyamoorthy wrote: How do you calculate the md5 checksum of a file? so far i got this, import md5 obj = md5.new() file = open( 'filename', 'rb') data = text.read() obj.update(data) checksum = md5.digest() Is this correct? Is there anything else i should do before comparing the checksum with the one provided for the file? Fredrik Lundh wrote: the script has some obvious bugs, but nothing you won't discover simply by running the program... (did you try that? what happened?) Nainto wrote: Take a look at: http://effbot.org/librarybook/md5.htm -------------- next part -------------- An HTML attachment was scrubbed... URL: From scott.daniels at acm.org Fri Mar 3 17:22:44 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 03 Mar 2006 14:22:44 -0800 Subject: Does '#hash' mean anything in IDLE? In-Reply-To: <7xk6bb45tf.fsf@ruckus.brouhaha.com> References: <1141331534.634181.275880@p10g2000cwp.googlegroups.com> <1141332159.625375.40540@e56g2000cwe.googlegroups.com> <3TINf.1719$No6.40137@news.tufts.edu> <1141394786.531934.134920@t39g2000cwt.googlegroups.com> <1141405501.950172.54370@i39g2000cwa.googlegroups.com> <4408a0d6$1@nntp0.pdx.net> <7xk6bb45tf.fsf@ruckus.brouhaha.com> Message-ID: <4408bfd9$1@nntp0.pdx.net> Paul Rubin wrote: > Scott David Daniels writes: >> And, for 2.4 or later: >> >> def letter_hash(word): >> return "".join(sorted(word)) >> >> sorted takes an iterable, and strings are iterables. > > I don't think the "hash" is really a hash in the normal sense--in > particular, it has to be collision-free. So I'd just call it > "sorted_word". Here's my version of the program: > > ================================================================ > from sets import Set "Cute" form for this: try: set except NameError: from sets import Set as set Then you get native sets for 2.4, and sets.Set for 2.3 > d = {} > for line in file('/usr/share/dict/words'): > word = line.strip().lower() > d.setdefault(sorted_word(word), Set()).add(word) > > print sorted(d.iteritems(), key=lambda (x,y): -len(y))[:1] ... > Note that I sorted the dictionary items in order to get the max > element. That is sort of bogus because it's an O(N log N) operation > while finding the maximum should only need O(N). But it leads to > a convenient spelling. It would be nice if "max" accepted a "key" > argument the way that the sorting functions do. Using a variant of DSU (Decorate-Sort-Undecorate) with max for S, rather than sort: print max((len(words), words) for words in d.itervalues()) or: size, words = max((len(words), words) for words in d.itervalues()) print size, sorted(words) --Scott David Daniels scott.daniels at acm.org From i.failed.turing.test at gmail.com Sat Mar 4 14:23:10 2006 From: i.failed.turing.test at gmail.com (David Treadwell) Date: Sat, 4 Mar 2006 14:23:10 -0500 Subject: Python advocacy in scientific computation Message-ID: <381B053C-8F56-4A5B-AD61-C775D19A0F5C@gmail.com> On Mar 4, 2006, at 5:55 AM, Dennis Lee Bieber wrote: > On Fri, 3 Mar 2006 22:05:19 -0500, David Treadwell > declaimed the following in > comp.lang.python: > > >> My ability to think of data structures was stunted BECAUSE of >> Fortran and BASIC. It's very difficult for me to give up my bottom-up >> programming style, even though I write better, clearer and more >> useful code when I write top-down. >> >> IIRC, during 1984, my senior year, BYTE magazine had a cover story on OOP. (OH, how I loved the cover art back in the day!) My impression after reading the article: WTF is that for? Every class I had which needed programming, be it CS or chemical engineering, taught it in a very linear, bottom-up fashion. First you read inputs, then do Foo, then do Bar, then do (fill in your favorite third-level word). It was even worse in the chemistry department. No chem major (other than myself, as I also was a chem eng major) had _any_ computer courses beyond the required Fortran 101. It was a struggle to get any chemistry student to do anything that required using LINPAC, Mathematical Recipes code or a plotting program. This level of absurdity reached its apex during grad skewl when I wrote a monolithic 30-page program in MS QuickBasic for Mac to simulate NMR spectra. No one else was ever able to understand how to use the program. Even worse, that 30-page program disappeared the day Mac System 7.0 was installed. The byte-compiled basic code became unreadable because System 7 permanently broke QuickBasic. The last program I wrote for anyone else's use was written in VBA/ Excel. I hated every minute of it, but the request was made because everyone has Excel, and nobody wanted to install Python. VBA has at least 3 API's running simultaneously (Excel, VBA-classic and VBA- pseudoOOP). Now that I know Py2App, that dragon has been slain. Which brings me to my last point: Why be beholden to the graces of a single-source supplier of a language or OS? Proprietary systems will always become either (a) extinct or (b) so crammed with legacy code they become unreliable. I still don't get OOP completely, but Python has helped a great deal. > FORTRAN was quite amenable to "top-down" design (which was barely > taught during my senior year: 1980; and I'm a CS major -- you don't > want > to see the text used for the "systems analysis" class; I don't recall > ever seeing a "requirement document" created in the entire text...) > > I've done lots of FORTRAN stuff where the main program was > interchangeable... > > program main > ... > call Initialize() > call Process() > call CleanUp() > stop > end > Sure. It seems logical now. But remember, I learned WatFiv Fortran, which came before even Fortran 77. I saw my first Fortran 95 code about two years ago. It took me a while to realize that what I was looking at _was_ Fortran! >> 3. I demand a general-purpose toolkit, not a gold-plated screwdriver. >> > > Would a gold-plated sonic screwdriver work? {Let's see how many > catch that reference} > Google makes this game too easy, but it's to Who you refer. How about _this_ reference: "What we all need is a left-handed monkey wrench." :--David From sRuEmMrOnVoEt at hotmail.com Tue Mar 21 14:02:43 2006 From: sRuEmMrOnVoEt at hotmail.com (Geoffrey Summerhayes) Date: Tue, 21 Mar 2006 14:02:43 -0500 Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1142589945.078364.32870@i39g2000cwa.googlegroups.com> <1142599685.186209.177630@j33g2000cwa.googlegroups.com> <1142612170.404220.23410@e56g2000cwe.googlegroups.com> <1142925259.468795.104500@t31g2000cwb.googlegroups.com> Message-ID: wrote in message news:1142925259.468795.104500 at t31g2000cwb.googlegroups.com... > After the basic fact of generating the exclusion - a considerable > achievement - the program should be interactive. What if the target set > has thousands or millions of elements? There should be a loop-like way > ('do' in Haskell, for example) to peel off the elements one-by-one and > then terminate. There is...(Q&D) 1 ?- generate_member(X,[1,2],3,[[and, [*,2], [or, [2,1,*], [1,2,*]]]]), write(X),nl,write('Is this the term you were looking for? (y/n):'), get(Y), ((Y is 121) -> true; fail). % 121 = 'y' [1, 1, 1] Is this the term you were looking for? (y/n):n [1, 1, 2] Is this the term you were looking for? (y/n):|: n [1, 2, 1] Is this the term you were looking for? (y/n):|: y Yes 2 ?- --- Geoff From fuzzyman at gmail.com Thu Mar 30 11:58:56 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 30 Mar 2006 08:58:56 -0800 Subject: Set Windows Environment Variable In-Reply-To: References: <1143723906.146263.136590@i40g2000cwc.googlegroups.com> Message-ID: <1143737936.678171.211010@z34g2000cwc.googlegroups.com> Magnus Lycka wrote: > Duncan Booth wrote: > > Fuzzyman wrote: > >> In the ``win32api`` package there is a ``GetEnvironmentVariable`` > >> function, but no ``SetEnvironmentVariable``. Any options ? > > > > No, your only option is to find a solution which doesn't involve changing > > another process's environment. > > Surely there must be a way to programatically set up the > environment variables for not yet started processes? I.e. > doing the same as when you manually change things in the > control panel. I'm pretty sure many Windows installers do > that, and while I suppose this is technically a registry > manipulation, I suspect there is a more direct API somewhere. I *believe* that ``SetEnvironmentVariable`` exists in the underlying windows API, but that it isn't wrapped by the win32api extension. I may be wrong. Fuzzyman http://www.voidspace.org.uk/python/index.shtml From aurora00 at gmail.com Tue Mar 21 13:21:34 2006 From: aurora00 at gmail.com (aurora) Date: Tue, 21 Mar 2006 10:21:34 -0800 Subject: Design mini-lanugage for data input References: <1142927112.502231.235450@t31g2000cwb.googlegroups.com> Message-ID: P.S. Also it is a 'mini-language' because it is an ad-hoc design that is good enough and can be easily implemented for a given problem. This is oppose to a general purpose solution like XML that is one translation from the original data format and carries too much baggages. > Just consider you don't have to enter two quotes for every string object > is almost liberating. These quotes are only artifacts for structured > data format. The idea to design a format convenient for human and let > code to parse and built the data structure. > > wy From kay.schluehr at gmx.net Wed Mar 8 01:23:02 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 7 Mar 2006 22:23:02 -0800 Subject: New python.org website In-Reply-To: References: <20060307223014.19227.qmail@web25715.mail.ukl.yahoo.com> Message-ID: <1141798982.758191.304090@i39g2000cwa.googlegroups.com> Michael wrote: > The new website is to blah. It's so light colored across the whole thing > that it kind of just melts away in my mind. Maybe giving a little color > in the menu bar on the right would help. My experience is that white is > a bad background color when over used. I agree. The text is too loud and the colors are too low. Otherwise Fredrik Lundh reminded me that there are no good PL language home pages out there at all. This shouldn't excuse a mediocre design but it softened my annoyance a little. From lycka at carmen.se Thu Mar 2 04:37:29 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 02 Mar 2006 10:37:29 +0100 Subject: Best python module for Oracle, but portable to other RDBMSes In-Reply-To: <1141243681.300714.225410@v46g2000cwv.googlegroups.com> References: <1140818561.458171.237850@p10g2000cwp.googlegroups.com> <1140826717.186051.261430@i39g2000cwa.googlegroups.com> <1141243681.300714.225410@v46g2000cwv.googlegroups.com> Message-ID: dananrg at yahoo.com wrote: > The other thing I didn't do a good job of explaining is that I want to > have a layer of abstraction between the underlying RDBMS and the > business logic. It's the business logic I want to use Python for, so > that would stay roughly the same between RDBMS changes, if we ever have > an RDBMS change. I agree that I probably have more things to worry if I > was to change RDBMS vendors than what I'm describing here. Have a look at SQLAlchemy. From fake at nospam.no Sun Mar 5 11:58:44 2006 From: fake at nospam.no (Blackbird) Date: Sun, 5 Mar 2006 17:58:44 +0100 Subject: raw strings and \ References: <1141548565.145199.145910@e56g2000cwe.googlegroups.com> <1141576051.081203.318010@e56g2000cwe.googlegroups.com> Message-ID: plahey at alumni.caltech.edu wrote: > Hi Duncan, > > thanks for the reply. I figured that this was a technical problem > associated with the parser. > > This one is going on my Python gotchas list. It is really silly from > an end user perspective to have \ not special in raw strings _except_ > if it is the last character. But at the parsing stage, it *is* somewhat special, even if it is not the last charater. E.g, a = r'check \' this' print a The second quote is not regarded as ending the string literal. From tprimke at interia.pl Sat Mar 25 05:36:38 2006 From: tprimke at interia.pl (TPJ) Date: 25 Mar 2006 02:36:38 -0800 Subject: Building Python extensions from sources on Windows Message-ID: <1143282998.090681.203630@u72g2000cwu.googlegroups.com> Hello, I have another, probably stupid, question. I'm working on some Python project, and I use some extensions written in C. I do all the development on my GNU/Linux box, so my setup.py script works just as it's supposed to work on a GNU/Linux system. But in the nearest future I'll have to make an executable program for Windows. I know, that there are some useful tools to make executables from Python programs for Windows (Py2Exe, PyInstaller - that's what I have heard about), but, as far as I understand the subject, I'll need the extensions modules (dll files? on my GNU/Linux system I always get some so files - shared libraries) in the compiled form in order to make any executable program. In the Python standard documentation I have read, that: "(...) Since the metadata is taken from the setup script, creating Windows installers is usually as easy as running: python setup.py bdist_wininst (...) If you have a non-pure distribution, the extensions can only be created on a Windows platform, and will be Python version dependent. (...)" And that's the problem: I understand the fact, that in order to build a non-pure distrubution, all the C sources have to be compiled (to dll libraries?). But there's the problem: I don't know which one compiler should I use. Do I have to use the same compiler, that the Python has been compiled with? If so, which one of the Windows compilers has been used to compile Python? Or perhaps could I use an another compiler? Which one, then? I have no idea what to do. I haven't done anything on Windows for so long... From http Mon Mar 6 16:26:48 2006 From: http (Paul Rubin) Date: 06 Mar 2006 13:26:48 -0800 Subject: slicing the end of a string in a list References: <1141357052.436244.24670@i39g2000cwa.googlegroups.com> <7xy7zs88xq.fsf@ruckus.brouhaha.com> <7xoe0o13kt.fsf@ruckus.brouhaha.com> Message-ID: <7xpskz1cyv.fsf@ruckus.brouhaha.com> Steve Holden writes: > >>>[line.rstrip() for line in open('C:\\switches.txt')] > > How would I manually close a file that's been opened this way? Or is > > it not possible in this case? Is it necessary? > > In CPython it's not strictly necessary to close the file, but other > implementations don't guarantee that a file will be closed after the > last reference is deleted. > > So for fullest portability it's better explicitly close the file. I wonder whether PEP 343 should be extended somehow. Hmm. [line.rstrip() for line within open('C:\\switches.txt')] # ugh!! Other ideas? From larry.bates at websafe.com Thu Mar 23 10:55:55 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 23 Mar 2006 09:55:55 -0600 Subject: encoding problems =?ISO-8859-1?Q?=28=E9_and_=E8=29?= In-Reply-To: References: Message-ID: Seems to work fine for me. >>> x="??" >>> x=x.replace('?','E') 'E\xc7' >>> x=x.replace('?','C') >>> x 'E\xc7' >>> x=x.replace('?','C') >>> x 'EC' You should also be able to use .upper() method to uppercase everything in the string in a single statement: tstr=ligneA.upper() Note: you should never use 'str' as a variable as it will mask the built-in str function. -Larry Bates bussiere bussiere wrote: > hi i'am making a program for formatting string, > or > i've added : > #!/usr/bin/python > # -*- coding: utf-8 -*- > > in the begining of my script but > > str = str.replace('?', 'C') > str = str.replace('?', 'E') > str = str.replace('?', 'E') > str = str.replace('?', 'E') > str = str.replace('?', 'E') > str = str.replace('?', 'E') > > > doesn't work it put me " and , instead of remplacing ? by E > > > if someone have an idea it could be great > > regards > Bussiere > ps : i've added the whole script under : > > > > > > > __________________________________________________________________________ > > > > > #!/usr/bin/python > # -*- coding: utf-8 -*- > import fileinput, glob, string, sys, os, re > > fichA=raw_input("Entrez le nom du fichier d'entree : ") > print ("\n") > fichC=raw_input("Entrez le nom du fichier de sortie : ") > print ("\n") > normalisation1 = raw_input("Normaliser les adresses 1 (ex : Avenue-> > AV) (O/N) ou A pour tout normaliser \n") > normalisation1 = normalisation1.upper() > > if normalisation1 != "A": > print ("\n") > normalisation2 = raw_input("Normaliser les civilit?s (ex : > Docteur-> DR) (O/N) \n") > normalisation2 = normalisation2.upper() > print ("\n") > normalisation3 = raw_input("Normaliser les Adresses 2 (ex : > Place-> PL) (O/N) \n") > normalisation3 = normalisation3.upper() > > > normalisation4 = raw_input("Normaliser les caracteres / et - (ex : > / -> ) (O/N) \n" ) > normalisation4 = normalisation4.upper() > > if normalisation1 == "A": > normalisation1 = "O" > normalisation2 = "O" > normalisation3 = "O" > normalisation4 = "O" > > > fiA=open(fichA,"r") > fiC=open(fichC,"w") > > > compteur = 0 > > while 1: > > ligneA=fiA.readline() > > > > if ligneA == "": > > break > > if ligneA != "": > str = ligneA > str = str.replace('a', 'A') > str = str.replace('b', 'B') > str = str.replace('c', 'C') > str = str.replace('d', 'D') > str = str.replace('e', 'E') > str = str.replace('f', 'F') > str = str.replace('g', 'G') > str = str.replace('h', 'H') > str = str.replace('i', 'I') > str = str.replace('j', 'J') > str = str.replace('k', 'K') > str = str.replace('l', 'L') > str = str.replace('m', 'M') > str = str.replace('n', 'N') > str = str.replace('o', 'O') > str = str.replace('p', 'P') > str = str.replace('q', 'Q') > str = str.replace('r', 'R') > str = str.replace('s', 'S') > str = str.replace('t', 'T') > str = str.replace('u', 'U') > str = str.replace('v', 'V') > str = str.replace('w', 'W') > str = str.replace('x', 'X') > str = str.replace('y', 'Y') > str = str.replace('z', 'Z') > > str = str.replace('?', 'C') > str = str.replace('?', 'C') > str = str.replace('?', 'E') > str = str.replace('?', 'E') > str = str.replace('?', 'E') > str = str.replace('?', 'E') > str = str.replace('?', 'E') > str = str.replace('?', 'E') > str = str.replace('?', 'E') > str = str.replace('?', 'E') > str = str.replace('?', 'A') > str = str.replace('?', 'A') > str = str.replace('?', 'A') > str = str.replace('?', 'A') > str = str.replace('?', 'A') > str = str.replace('?', 'A') > str = str.replace('?', 'A') > str = str.replace('?', 'A') > str = str.replace('?', 'A') > str = str.replace('?', 'A') > str = str.replace('?', 'I') > str = str.replace('?', 'I') > str = str.replace('?', 'I') > str = str.replace('?', 'I') > str = str.replace('?', 'O') > str = str.replace('?', 'O') > str = str.replace('?', 'O') > str = str.replace('?', 'O') > str = str.replace('?','U') > str = str.replace(' ', ' ') > str = str.replace(' ', ' ') > str = str.replace(' ', ' ') > > > > if normalisation1 == "O": > str = str.replace('AVENUE', 'AV') > str = str.replace('BOULEVARD', 'BD') > str = str.replace('FAUBOURG', 'FBG') > str = str.replace('GENERAL', 'GAL') > str = str.replace('COMMANDANT', 'CMDT') > str = str.replace('MARECHAL', 'MAL') > str = str.replace('PRESIDENT', 'PRDT') > str = str.replace('SAINT', 'ST') > str = str.replace('SAINTE', 'STE') > str = str.replace('LOTISSEMENT', 'LOT') > str = str.replace('RESIDENCE', 'RES') > str = str.replace('IMMEUBLE', 'IMM') > str = str.replace('IMEUBLE', 'IMM') > str = str.replace('BATIMENT', 'BAT') > > if normalisation2 == "O": > str = str.replace('MONSIEUR', 'M') > str = str.replace('MR', 'M') > str = str.replace('MADAME', 'MME') > str = str.replace('MADEMOISELLE', 'MLLE') > str = str.replace('DOCTEUR', 'DR') > str = str.replace('PROFESSEUR', 'PR') > str = str.replace('MONSEIGNEUR', 'MGR') > str = str.replace('M ME','MME') > > > if normalisation3 == "O": > str = str.replace('PLACE', 'PL') > str = str.replace('IMPASSE', 'IMP') > str = str.replace('ESPLANADE', 'ESP') > str = str.replace('ROND POINT', 'RPT') > str = str.replace('ROUTE', 'RTE') > str = str.replace('PASSAGE', 'PAS') > str = str.replace('SQUARE', 'SQ') > str = str.replace('ALLEE', 'ALL') > str = str.replace('ESCALIER', 'ESC') > str = str.replace('ETAGE', 'ETG') > str = str.replace('PORTE', 'PTE') > str = str.replace('APPARTEMENT', 'APT') > str = str.replace('APARTEMENT', 'APT') > str = str.replace('AVENUE', 'AV') > str = str.replace('BOULEVARD', 'BD') > str = str.replace('ZONE D ACTIVITE', 'ZA') > str = str.replace('ZONE D ACTIVITEE', 'ZA') > str = str.replace('ZONE D AMENAGEMENT CONCERTE', 'ZAC') > str = str.replace('ZONE D AMENAGEMENT CONCERTEE', 'ZAC') > str = str.replace('ZONE INDUSTRELLE', 'ZI') > str = str.replace('CENTRE COMMERCIAL', 'CCAL') > str = str.replace('CENTRE', 'CTRE') > str = str.replace('C.CIAL','CCAL') > str = str.replace('CTRE CIAL','CCAL') > str = str.replace('CTRE CCAL','CCAL') > str = str.replace('GALERIE','GAL') > str = str.replace('MARTYR', 'M') > str = str.replace('ANCIENS', 'AC') > str = str.replace('ANCIEN', 'AC') > str = str.replace('REVEREND PERE','R P') > > if normalisation4 == "O": > str = str.replace(';\"', ' ') > str = str.replace('\"', ' ') > str = str.replace('\'', ' ') > str = str.replace('-', ' ') > str = str.replace(',', ' ') > str = str.replace('\\', ' ') > str = str.replace('\/', ' ') > str = str.replace('&', ' ') > str = str.replace('%', ' ') > str = str.replace('*', ' ') > str = str.replace(' ', ' ') > str = str.replace('.', ' ') > str = str.replace('_', ' ') > str = str.replace(' ', ' ') > str = str.replace(' ', ' ') > str = str.replace('?', ' ') > str = str.replace('%', ' ') > str = str.replace('|', ' ') > > > > > > > > > > > > > str = str.replace(' ', ' ') > str = str.replace(' ', ' ') > str = str.replace(' ', ' ') > fiC.write(str) > compteur += 1 > print compteur, "\n" > > > print "FINIT" > fiA.close() > fiC.close() From cvanarsdall at mvista.com Wed Mar 22 15:17:59 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 22 Mar 2006 12:17:59 -0800 Subject: Why TypeError: 'str' object is not callable? In-Reply-To: <1143058248.958219.211950@i40g2000cwc.googlegroups.com> References: <1143058248.958219.211950@i40g2000cwc.googlegroups.com> Message-ID: <4421B0F7.1060203@mvista.com> Randall Parker wrote: > Using Python 2.4.2 on Windows 2000 in SPE. > > Getting: > TypeError: 'str' object is not callable > > on this line: > > You have a boo boo > TmpErrMsg1 = "State machine %s " (StateMachineName) > Should be TmpErrMsg1 = "State machine %s " %(StateMachineName) > In Winpdb 1.0.6 the StateMachineName is of type str in the Namespace | > Local window of local variables. It even has the string value I expect > of 'ExampleAO'. That string variable was originally set in another > variable by reading a socket packet field. Then it was assigned to > StateMachineName. > > I'm not using str as a variable. I searched all my source code. > > So why can't I do this? > > Is there a way to test what "str" is? Maybe importing the minidom > messed up what str is? This code used to work. I am trying to figure > out what caused it to cease to work. > > Any ideas? > > -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From kent at kentsjohnson.com Wed Mar 22 11:19:31 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 22 Mar 2006 11:19:31 -0500 Subject: string.upto() and string.from() In-Reply-To: References: <1143038492.748562.267150@i40g2000cwc.googlegroups.com> Message-ID: <442173ff$1_3@newspeer2.tds.net> Fredrik Lundh wrote: > ikshefem at gmail.com wrote: > > >>I often need to re-code for myself a small code snippet to define >>string.upto() and string.from(), which are used like : FWIW this is pretty easy to do with str.split() and rsplit(): >> >># canonical examples >> >>>"1234456789".upto("45") >> >>'1234' "1234456789".split("45", 1)[0] '1234' >> >>>"123456dd987".from('d') >> >>'d987' "1234456789".rsplit("45", 1)[-1] '6789' >> >># if not found, return whole string >> >>>"hello, world !".upto("#") >> >>"hello, world !" "hello, world !".split("#", 1)[0] 'hello, world !' >> >>>u"hello, world !".from("#") >> >>u"hello, world !" "hello, world !".rsplit("#", 1)[-1] 'hello, world !' Kent From uval at rz.uni-karlsruhe.de Thu Mar 9 17:31:43 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Thu, 09 Mar 2006 23:31:43 +0100 Subject: A better RE? In-Reply-To: References: Message-ID: Magnus Lycka wrote: > I want an re that matches strings like "21MAR06 31APR06 1236", > where the last part is day numbers (1-7), i.e it can contain > the numbers 1-7, in order, only one of each, and at least one > digit. I want it as three groups. I was thinking of > > r"(\d\d[A-Z]\d\d) (\d\d[A-Z]\d\d) (1?2?3?4?5?6?7?)" > > but that will match even if the third group is empty, > right? Does anyone have good and not overly complex RE for > this? > > P.S. I know the "now you have two problems reply..." >>> txt = "21MAR06 31APR06 1236" >>> m = '(?:JAN|FEB|MAR|APR|MAI|JUN|JUL|AUG|SEP|OCT|NOV|DEZ)' # non capturing group (:?) >>> p = re.compile(r"(\d\d%s\d\d) (\d\d%s\d\d) (?=[1234567])(1?2?3?4?5?6?7?)" % (m,m)) >>> p.match(txt).group(1) '21MAR06' >>> p.match(txt).group(2) '31APR06' >>> p.match(txt).group(3) 1236 From cito at online.de Fri Mar 24 16:29:48 2006 From: cito at online.de (Christoph Zwerschke) Date: Fri, 24 Mar 2006 22:29:48 +0100 Subject: What's The Best Editor for python In-Reply-To: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> References: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> Message-ID: Just because nobody has mentioned them so far: - SciTe is a perfect editor for Pyhton on Win and Linx - PyScripter is a wonderful IDE (but only on Win) - DrPython is a nice platform independent editor/mini-IDE There is no one editor that could be called the best one, but there are many which are far better suited for Python than the simple standard text editors (Notepad & Co). Maybe you prefer to have one editor that suits all your programming and typing needs (not only Python), so you don't have to use different editors Python, HTML, XML, config files etc. SciTe performs very well here, and of course also Emacs... -- Christoph From pmartin at snakecard.com Sun Mar 26 13:09:15 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sun, 26 Mar 2006 12:09:15 -0600 Subject: PIL & image size reduction script Message-ID: Hi, Thanks to the NG, I got the script hereunder working. 1) I am not certain that the call to convert does much (checking the doc) 2) Can this be improved as far as the final image size in (X,Y) ? For instance, passing a large .jpg with a target byte size of 7000, I get final (X,Y) results around (213, 174) ... but might want to strech it a bit while keeping the byte size. Thanks, Philippe #******************************************************************************* def Image_Reduce(self, p_filename, p_size): BASE_SIZE = 400.0 l_im = Image.open(p_filename) l_size = l_im.size if l_size[0] > l_size[1]: l_ratio = BASE_SIZE / l_size[0] l_x_size = l_ratio * l_size[0] l_y_size = l_ratio * l_size[1] else: l_ratio = BASE_SIZE / l_size[1] l_x_size = l_ratio * l_size[0] l_y_size = l_ratio * l_size[1] # l_im.show() l_image = l_im.resize( (l_x_size, l_y_size)) l_image = l_image.convert(mode="RGB", palette=Image.ADAPTIVE) l_done = False l_tmp_file_name = 'sc_tmp_file.jpg' while False == l_done: l_image.save(l_tmp_file_name) l_st = os.stat(l_tmp_file_name) print 'HERE ', l_st if p_size < l_st[6]: l_ratio -= 0.005 print 'NEW RATIO = ', l_ratio l_x_size = l_ratio * l_size[0] l_y_size = l_ratio * l_size[1] l_image = l_im.resize( (l_x_size, l_y_size)) else: l_done = True l_image.show() print l_image.size From g.horvath at gmx.at Fri Mar 31 23:44:14 2006 From: g.horvath at gmx.at (Gregor Horvath) Date: Sat, 01 Apr 2006 06:44:14 +0200 Subject: Looking for a language/framework In-Reply-To: <442daf37$1@nntp0.pdx.net> References: <1143559444.045808.38790@u72g2000cwu.googlegroups.com> <1hcwg6n.b3jwv5xq910tN%aleaxit@yahoo.com> <1143837635.846033.204910@u72g2000cwu.googlegroups.com> <442daf37$1@nntp0.pdx.net> Message-ID: > > But what you overlook is SQL's strength: > > SQL can be translated into _very_ efficient query plans w/o changing > the SQL. SQL's query optimizers (more properly, de-pessimizers) give Premature optimization is the root of all evil. On the top level of an appliciation the goal is to only have problem or domain specific code. Middelware or ORM is a way to this goal because it encapsulates and hides the technical details of persistence and helps for cleaner code. -- Mit freundlichen Gr??en, Ing. Gregor Horvath, Industrieberatung & Softwareentwicklung http://www.gregor-horvath.com From jess.austin at gmail.com Sat Mar 4 13:45:12 2006 From: jess.austin at gmail.com (jess.austin at gmail.com) Date: 4 Mar 2006 10:45:12 -0800 Subject: generators shared among threads Message-ID: <1141497912.606351.232440@j33g2000cwa.googlegroups.com> hi, This seems like a difficult question to answer through testing, so I'm hoping that someone will just know... Suppose I have the following generator, g: def f() i = 0 while True: yield i i += 1 g=f() If I pass g around to various threads and I want them to always be yielded a unique value, will I have a race condition? That is, is it possible that the cpython interpreter would interrupt one thread after the increment and before the yield, and then resume another thread to yield the first thread's value, or increment the stored i, or both, before resuming the first thread? If so, would I get different behavior if I just set g like: g=itertools.count() If both of these idioms will give me a race condition, how might I go about preventing such? I thought about using threading.Lock, but I'm sure that I don't want to put a lock around the yield statement. thanks, Jess From csr21 at cam.ac.uk Mon Mar 20 16:27:54 2006 From: csr21 at cam.ac.uk (Christophe Rhodes) Date: Mon, 20 Mar 2006 21:27:54 +0000 Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <441ef3a2$0$15789$14726298@news.sunsite.dk> Message-ID: [ note followups ] Mark Carter writes: > I'd like to propose a coding challenge of my own. The challenge is to > reproduce the TEA (Tiny Encryption Algorith): > http://www.simonshepherd.supanet.com/tea.htm > in your language of choice. Here's mine, in Common Lisp. (defmacro define-tea-pair ((encrypt decrypt) (delta n) (i1 j1 i2 j2)) `(macrolet ((32bitize (form) `(logand ,form #xffffffff)) (tea-kernel (x i j) `(logxor (+ (ash ,x 4) (aref key ,i)) (+ ,x sum) (+ (ash ,x -5) (aref key ,j)))) (tea-loop ((text n sum) &body body) `(let ((result (make-array 2 :element-type '(unsigned-byte 32))) (y (aref ,text 0)) (z (aref ,text 1))) (do ((n ,n (- n 1)) (sum ,sum)) ((<= n 0) (prog1 result (setf (aref result 0) y (aref result 1) z))) , at body)))) (defun ,encrypt (plaintext key &aux (delta ,delta)) (declare (type (simple-array (unsigned-byte 32) (2)) plaintext) (type (simple-array (unsigned-byte 32) (4)) key)) (tea-loop (plaintext ,n 0) (setq sum (32bitize (+ sum delta)) y (32bitize (+ y (tea-kernel z ,i1 ,j1))) z (32bitize (+ z (tea-kernel y ,i2 ,j2)))))) (defun ,decrypt (ciphertext key &aux (delta ,delta)) (declare (type (simple-array (unsigned-byte 32) (2)) ciphertext) (type (simple-array (unsigned-byte 32) (4)) key)) (tea-loop (ciphertext ,n (32bitize (* ,n delta))) (setq z (32bitize (- z (tea-kernel y ,i2 ,j2))) y (32bitize (- y (tea-kernel z ,i1 ,j1))) sum (32bitize (- sum delta))))))) (define-tea-pair (encipher decipher) (#x9e3779b9 32) (0 1 2 3)) So far, so ordinary; only marginally shorter than the C version; I'm certainly nowhere near Pascal's 14 lines, although my version has the advantage over his that each constant is mentioned only once, and all quantities derived from it are computed at compile-time; I can define a different pair with (define-tea-pair (eprime dprime) (#xabcdef01) (3 1 2 0)) and the new functions are inverses of each other as before. The other thing that might be of interest is the inner loop. There are no declarations other than the argument declarations, and all the code that I have written is portable Common Lisp, and should work in any conforming implemenation. In SBCL (on the PowerPC; other platforms are similar), the inner loop for ENCIPHER is addis $nl0,$nl3,-25033 addi $nl3,$nl0,31161 rlwinm $nl5,$nl2,4,0,27 lwz $nl6,1($fdefn) add $nl6,$nl5,$nl6 add $nl0,$nl2,$nl3 xor $cfunc,$nl6,$nl0 rlwinm $nl0,$nl2,27,5,31 mr $nl5,$nl0 lwz $nl6,5($fdefn) add $nl6,$nl5,$nl6 xor $nl6,$cfunc,$nl6 add $nl1,$nl1,$nl6 rlwinm $nl5,$nl1,4,0,27 lwz $nl6,9($fdefn) add $nl6,$nl5,$nl6 add $nl0,$nl1,$nl3 xor $cfunc,$nl6,$nl0 rlwinm $nl0,$nl1,27,5,31 mr $nl5,$nl0 lwz $nl6,13($fdefn) add $nl6,$nl5,$nl6 xor $nl6,$cfunc,$nl6 add $nl2,$nl2,$nl6 addi $nl4,$nl4,-4 cmpwi cr0,$nl4,0 bt gt,l0 and while this may be opaque to some readers, the point is that it is pretty much comparable to the C code in performance (the differences between this disassembly and gcc -O2 lie in the fact that SBCL's instruction scheduler is pretty much nonexistent on the PowerPC architecture). Christophe From duncan.booth at invalid.invalid Thu Mar 16 03:49:35 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Mar 2006 08:49:35 GMT Subject: Printable string for 'self' References: <1142492427.064713.312890@j33g2000cwa.googlegroups.com> Message-ID: Michael Tobis wrote: > I got in some trouble in these parts a few months back for advocating > some sort of immutable reference, like > > fred -> C("fred") > > where any reassignment of the refernce during the lifetime of the > referent would raise an exception. This seems to be seen as wrongheaded > by greater pythonistas than myself. I don't fully understand *why* > this is a bad idea, but my intuitive idea that it would be very > valuable has gone away. > >>> fred = C("fred") >>> jim = fred RebindingError: cannot rebind to name "jim" >>> def showit(x): print x >>> showit(fred) RebindingError: cannot rebind to name "x" >>> fred.amethod() RebindingError: cannot rebind to name "self" >>> fred.aclassmethod() That works! >>> sys.getrefcount(fred) RebindingError: cannot rebind to name "object" >>> del fred >>> What were you planning to do with this object exactly that didn't involve binding it to any other names during its lifetime? From fredrik at pythonware.com Sat Mar 11 02:57:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 11 Mar 2006 08:57:59 +0100 Subject: Python cleanup on exit References: <4411C2D5.7010407@gmail.com> Message-ID: Jacob Kroon wrote: > I'm working on a library written in C using GObject, which i > provide python bindings for using pygtk. When I checked the > library for memory leaks using valgrind, I noticed that none > of the objects I created in the script (that is they are global in > the script) were deleted on exit. After some googling I came > to the conslusion that the python interpreter doesn't "cleanup" > after itself on exit, because of shutdown performance. > > This means that if I want to check the library for mem leaks I have > to either manually "del myobject1, delmyobject2 ..." at the end > of the scripts, or make sure that all objects get created in a > function scope, so that python will delete them for me when > the interpreter exits the scope. are the objects persistent on a system-wide level ? if not, what's the problem ? the operating system will clean them all out much faster than you can do it yourself. (the usual way to look for true leaks is to run the relevant code in a loop. stuff that's left for the operating system to throw away very seldom qualifies as "leaks"). From nephish at xit.net Mon Mar 6 22:43:34 2006 From: nephish at xit.net (nephish at xit.net) Date: 6 Mar 2006 19:43:34 -0800 Subject: need a start point for wsdl Message-ID: <1141703014.199482.33860@i39g2000cwa.googlegroups.com> hello there, i have recently been tasked with grabbing info to pipe into our database from an information server. The server guys told me i need to grab their wsdl file. Untill earlier this afternoon, i had no idea what wsdl is. From what i gather, it is much like SOAP. So anyway, any pythoneers out there make use of this? Know of some good documentation or even a book ? i would appreciate very much a good start point to begin learning how to pull this off. thanks From python at rcn.com Tue Mar 14 03:51:35 2006 From: python at rcn.com (Raymond Hettinger) Date: 14 Mar 2006 00:51:35 -0800 Subject: Memory visualization In-Reply-To: <1142318282.330669.129630@z34g2000cwc.googlegroups.com> References: <1142318282.330669.129630@z34g2000cwc.googlegroups.com> Message-ID: <1142326295.356619.136560@i39g2000cwa.googlegroups.com> [bearophile] > During the execution of a Icon script there are ways to visualize the > memory: > http://www.cs.arizona.edu/icon/progvis/memmon/memmon.htm . . . > I'd like to know if for Python there is a similar program to > dynamically see the memory in a similar way. > If such tool doesn't exist yet, I'd like to know if it may be diffifult > to create it. Yes, it would be difficult. Python gets chunks of memory from the o/s -- those may not be contiguous. Python has some internal object reuse tricks such that a chuck of memory may be tied-up in a free-list though no active object is alive. Extensions can call their own malloc and free so it would be difficult to ensure that you catch those. Some objects like lists and dicts have chunks of partially used memory that allow room for growth. That being said, there is likely some interesting things that could be done in C by exploiting tp_traverse and by hacking Python's internal object allocator. Raymond From fredrik at pythonware.com Wed Mar 22 04:59:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Mar 2006 10:59:37 +0100 Subject: multiple assignment References: <1143018514.721434.246450@i39g2000cwa.googlegroups.com> Message-ID: Christoph Zwerschke wrote: > You're right, that would not be so far off. > But then, the following should be also supported: > > *x, y = a # x, y = a[:-1], y = a[-1] > x, *y, z = a # x, y, z = a[0], a[1:-1], a[-1] > > Of course, there can be only one variable with an asterisk. > (But note that in the situation of a function taking parameters, that > variable must always be the last.) > > But I don't know if this is really useful enough... things like this are proposed from time to time (I haven't looked, but there might even be a PEP somewhere). however, function calls and assignments are two different things, and I'm not convinced that it's not yet another hypergeneralization... From exarkun at divmod.com Sun Mar 12 22:41:11 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 12 Mar 2006 22:41:11 -0500 Subject: "RuntimeError: dictionary changed size during iteration" ; Good atomic copy operations? In-Reply-To: <1142214997.549342.123440@e56g2000cwe.googlegroups.com> Message-ID: <20060313034111.6122.1254298352.divmod.quotient.15749@ohm> On 12 Mar 2006 17:56:37 -0800, Raymond Hettinger wrote: > >Thinking about future directions for Python threading, I wonder if >there is a way to expose the GIL (or simply impose a temporary >moratorium on thread switches) so that it becomes easy to introduce >atomicity when needed: > > gil.acquire(BLOCK=True) > try: > #do some transaction that needs to be atomic > finally: > gil.release() > This is vaguely possible using sys.setcheckinterval() now, although one has to pick a ridiculously large number and hope that the atomic operation takes fewer than that many opcodes. Spelling "do not switch threads" as sys.setcheckinterval(None) seems somewhat natural, though. Perhaps that would be a fruitful direction to explore. Jean-Paul From belred at gmail.com Tue Mar 21 09:53:32 2006 From: belred at gmail.com (Bryan) Date: Tue, 21 Mar 2006 06:53:32 -0800 Subject: ANN: pywinauto 0.3.0 released - now localization proof In-Reply-To: <1142889140.804003.85080@i40g2000cwc.googlegroups.com> References: <1142889140.804003.85080@i40g2000cwc.googlegroups.com> Message-ID: <4420136C.8000504@gmail.com> mark.m.mcmahon at gmail.com wrote: > ANN: pywinauto 0.3.0 released - now localization proof > > Hi, > > The 0.3.0 release of pywinauto is now available. > > pywinauto is a set of open-source (LGPL) modules for using Python as a > GUI automation 'driver' for Windows NT based Operating Systems > (NT/W2K/XP). > > SourceForge project page: > http://sourceforge.net/projects/pywinauto > > Download from SourceForge > http://sourceforge.net/project/showfiles.php?group_id=157379 > > > Here is the list of changes from 0.2.5: > > 0.3.0 Added Application data - now useful for localization testing > ------------------------------------------------------------------ > 20-Mar-2006 > > * Added automatic Application data collection which can be used > when running the same test on a different spoken language > version. Support is still preliminary and is expected to change. > Please treat as early Alpha. > > If you have a different language version of Windows then you can > try this out by running the notepad_fast.py example with the > langauge argument e.g. :: > > examples\notepad_fast.py language > > This will load the application data from the supplied file > notepad_fast.pkl and use it for finding the right menu items > and controls to select. > > * Test implementation to make it easier to start using an > application. Previously you needed to write code like :: > > app = Application().connect_(title = 'Find') > app.Find.Close.Click() > app.NotePad.MenuSelect("File->Exit") > > 1st change was to implement static methods ``start()`` and > ``connect()``. These methods return a new Application instance > so the above code becomes:: > > app = Application.connect(title = 'Find') > app.Find.Close.Click() > app.NotePad.MenuSelect("File->Exit") > > I also wanted to make it easier to start working with a simple > application - that may or may not have only one dialog. To make > this situation easier I made ``window_()`` not throw if the > application has not been ``start()ed`` or ``connect()ed`` first. > This leads to simpler code like:: > > app = Application() > app.Find.Close.Click() > app.NotePad.MenuSelect("File->Exit") > > What happens here is that when you execute any of > Application.window_(), Application.__getattr__() or > Application.__getitem__() when the application hasn't been connected > or started. It looks for the window that best matches your > specification and connects the application to that process. > > This is extra functionality - existing connect_() and > start_() methods still exist > > * Fixed HwndWrapper.SetFocus() so that it would work even if > the window was not in the foreground. (it now makes the window > foreground as well as giving it focus). This overcomes a > restriction in Windows where you can only change the foreground > window if you own the foreground window. > > * Changed some 2.4'isms that an anonymous commenter left on my > blog :-) with these changes pywinauto should run on Python 2.3 > (though I haven't done extensive testing). > > * Commented out > controls.common_controls.TabControlWrapper.GetTabState() > and TabStates() as these did not seem to be returning valid > values anyway. > > * Fixed documentation issues were parts of the documentation were > not getting generated to the HTML files. > > * Fixed issue where MenuSelect would sometimes not work as > expected. Some Menu actions require that the window that owns the > menu be active. Added a call to SetFocus() before selecting a menu > item to ensure that the window was active. > > * Fixed Bug 1452832 where clipboard was not closed in > clipboard.GetData() > > * Added more unit tests now up to 248 from 207 > > > If you want to follow this project then please sign up to the mailing > list: > https://lists.sourceforge.net/mailman/listinfo/pywinauto-users > > Thanks > Mark > i just tried the notepad demo and it's very nice. the only thing was in the demo it shows one Click() method to close the notepadabout dialog. but for me on windows xp media edition, it took two Click() methods. the first click clearly had the button depressed and the second click released the button back up. is this a bug in 0.3.0? or is it the new way of doing it... two clicks for each button? also, i would be really nice if the FAQ mentioned where you could get free or opensourced spy utilities so you could spy on controls and get their id values or internal names. thanks, bryan From deets at nospam.web.de Tue Mar 7 11:50:21 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 07 Mar 2006 17:50:21 +0100 Subject: inserting into a list References: <475qs4Fdp9mhU1@uni-berlin.de> Message-ID: <475s0sFe4g15U1@uni-berlin.de> John Salerno wrote: > Diez B. Roggisch wrote: > >> Why don't you just _try_ that? It would have been way faster than to ask >> questions you can easily answer yourself. > > I did try it, but I was still hoping for an explanation, which I've also > gotten from you guys, some in nicer terms than others. You got an explanation to your first question from me. But you obviously _didn't_ try your second one. Which would be a no-brainer as Warby's reply shows, and given that you already knew how to insert a single element list I consider it being not so nice of _you_ not to do so, but instead post before you tried. Diez From tjreedy at udel.edu Sat Mar 18 21:58:48 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 18 Mar 2006 21:58:48 -0500 Subject: Is there no end to Python? References: <1142622194.560240.4330@j52g2000cwj.googlegroups.com><1142627765.683262.27120@i39g2000cwa.googlegroups.com><1142677667.002061.269760@p10g2000cwp.googlegroups.com><441c2abd$1@nntp0.pdx.net> <1142705943.457304.109960@e56g2000cwe.googlegroups.com> Message-ID: "Kamilche" wrote in message news:1142705943.457304.109960 at e56g2000cwe.googlegroups.com... > arcane code' crowd. Sets - when I played with them, they were slower > than doing the equivalent code with dicts. It's got to be a reliable, > compelling feature, before I'll add it to my arsenal. In 2.3, sets was, I believe, a module written in Python on top of the dict type. In 2.4, set() is a builtin type written in C adapting the C code of dicts but without the overhead of values, and with set rather than dict oriented methods. tjr From mtebeka at qualcomm.com Thu Mar 9 02:57:32 2006 From: mtebeka at qualcomm.com (Miki Tebeka) Date: Thu, 09 Mar 2006 09:57:32 +0200 Subject: My OSDC.il Python Talks Message-ID: Hello All, Last week I gave three Python talks at OSDC.il (http://osdc.org.il/). If you are truly bored you can find the talks and demo source code at http://one.fsphost.com/tebeka/OSDC/ Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://one.fsphost.com/tebeka/ The only difference between children and adults is the price of the toys From reply.in.the.newsgroup at my.address.is.invalid Sun Mar 26 12:52:27 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sun, 26 Mar 2006 19:52:27 +0200 Subject: Cookbook for beginners? References: Message-ID: <9hkd22te3243kn9d8qs66o5rvlata7dtrs@4ax.com> Aahz: >If you were going to name three or five essential recipes from the >Python Cookbook suitable for beginners, what would you pick? >Yes, this is for _Python for Dummies_, so idioms that aren't in the >Cookbook are also fine. Constants Static methods / Class methods Bunch TaskQueue (Queue for easy and safe multithreading) A decorator for type checking of function arguments, and/or for require/ensure, and/or for similar features of other languages that people find missing in Python. Properties and in particular lazy properties. Why and how to avoid getters/setters. Dynamically import a module (name known at runtime, may or may not be present). Unittest/doctest. From simon at brunningonline.net Thu Mar 2 06:38:14 2006 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 2 Mar 2006 11:38:14 +0000 Subject: Shell Navigation In-Reply-To: References: Message-ID: <8c7f10c60603020338p639b1b08hb108d64640f08161@mail.gmail.com> On 3/2/06, William Meyer wrote: > I am having trouble with the python interactive shell. The arrow keys render as > ^[[D, ^[[A, etc making line editing impossible. The arrow keys (and function > keys) work fine in bash, but in the python shell they are printed. Any ideas > what is going on? Sounds like a readline problem. Your OS? How did you install Python? -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From donn at drizzle.com Mon Mar 27 01:40:52 2006 From: donn at drizzle.com (Donn Cave) Date: Mon, 27 Mar 2006 06:40:52 -0000 Subject: access mbx files? References: Message-ID: <1143441652.512507@yasure.drizzle.com> Quoth "David Isaac" : | "Alan Isaac" wrote in message | news:T9zVf.1942$b07.1558 at trnddc05... |> Should I be able to access mail messages in Mahogany mail's mbx |> format using the Python mailbox module? If so, can someone |> please post a working example? If not, can you please |> point me to documentation of the file format or better yet |> Python code to parse it? | | OK, from what I have been able to learn (not a lot), | my original question may boiled down to: | has anyone wrapped the cclient library for Python? ... | Will I need to pursue this, or is this functionality | somewhere in the mailbox module. (And if not, | can someone please explain why not?) In the end it depends on what you want to do. But to simply read the messages out of an MBX format folder, without necessarily accounting for concurrent access from other applications, c-client is overkill. If you look at the folder file - after the 4K header (2K? I forget), the structure is <1-line-header>, and the header doesn't carry a lot of information that's of supreme importance. The one thing you want to extract from it is the length field, which allows you to index to the next header. The message data is . As far as I can recall, that's all there is to it. I suppose it isn't supported by the mailbox module basically because it isn't all that commonly encountered. It may be more common on mail servers, but there it's email net protocol data, POP or IMAP. If Mahogany has been using this format for `local' folders (i.e., via filesystem), I think that may have been kind of poor judgement on the part of its developers. Donn Cave, donn at drizzle.com From trentm at ActiveState.com Fri Mar 10 18:07:17 2006 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 10 Mar 2006 15:07:17 -0800 Subject: lighter weight options to Python's logging package? In-Reply-To: <17426.1316.38093.513429@montanaro.dyndns.org> References: <17426.1316.38093.513429@montanaro.dyndns.org> Message-ID: <20060310230717.GA17067@activestate.com> [skip at pobox.com wrote] > We use the standard logging package and frequently bump into performance > issues with it (we log a lot of information). When that happens, we then go > through our code and dump a bunch of logging calls we think we can live > without. This invariably causes problems because we get overzealous and > delete something we needed and are then unable to do some bit of post-mortem > debugging until we add back in the missing logging and cut another release. > > Before I consider writing something from scratch, is there something lighter > weight "floating around" out there already? Do you have any profile information for where in the logging package the time is being spent? I don't know how much of a perf issue it is for you. Perhaps tweaking your usage of the logging package (perhaps using custom Loggers, Filters, outputters, etc.) could be made "good enough". Trent -- Trent Mick TrentM at ActiveState.com From luca.tavoletti at gmail.com Wed Mar 15 06:39:54 2006 From: luca.tavoletti at gmail.com (lux) Date: 15 Mar 2006 03:39:54 -0800 Subject: Button and Key Event Message-ID: <1142422794.772939.161390@z34g2000cwc.googlegroups.com> Hi, how to enable EVT_CHAR or EVT_KEY_DOWN in a wxButton? Thank's, Luca From rrr at ronadam.com Wed Mar 29 02:31:19 2006 From: rrr at ronadam.com (Ron Adam) Date: Wed, 29 Mar 2006 01:31:19 -0600 Subject: any() and all() on empty list? In-Reply-To: <42qWf.18211$uX5.7574@tornado.texas.rr.com> References: <7x3bh1x0ym.fsf@ruckus.brouhaha.com> <42qWf.18211$uX5.7574@tornado.texas.rr.com> Message-ID: Paul McGuire wrote: > "Paul Rubin" wrote in message > news:7x3bh1x0ym.fsf at ruckus.brouhaha.com... > To my mind, the *meaning* of all() is that every element in the list asserts > True. But this is with an initial assumption that all() is False, unless I > test every value and find them to be True. Since I assume False to begin > with, I get no values in the list to contradict the assumption, and so > all([]) returns False. Looking at in a different way... If we consider also having a function none() (for comparison), would it be consistent with all()? def none(S): for x in S: if x: return False return True any([]) -> False none([]) -> True (same as 'not any(S)') all([]) -> True ? False I think I agree that all() should have an initial presumption of being False. Looking at it in yet another way... (yes, not as efficient) def all(S): S_ = [x for x in S if x] return S_ == S def any(S): S_ = [x for x in S if x] return S_ != [] def none(S): S_ = [x for x in S if x] return S_ == [] In this view and empty set can be True for all(). Is it posible 'all([])' is undefined? Here, none() and all() return contradicting values. So maybe the correct version may be... def all(S): if S == []: return False for x in S: if x return True return False I think a few valid actual use case examples could clear it up. What makes the most sense? Cheers, Ron From hancock at anansispaceworks.com Fri Mar 10 06:31:17 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 10 Mar 2006 05:31:17 -0600 Subject: Python Evangelism In-Reply-To: <44114A97.3060200@optushome.com.au> References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> <1141980825.306512.59850@j33g2000cwa.googlegroups.com> <44114A97.3060200@optushome.com.au> Message-ID: <20060310053117.06d505a4@samwise.anansi> On Fri, 10 Mar 2006 20:44:55 +1100 Tim Churches wrote: > I think that Glykon should be invited to be the sponsoring > divinity for PyCon next year. I hear that worship of pagan > gods is, like everything else, bigger in Texas. Ignoring the silly Python jokes, *is* PyCON going to be in Texas next year? I wasn't sure what would happen, since it was in Washington DC the last (first?) 3 years, according to the website. Would be great for me if true, since I live there. -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From duncan.booth at invalid.invalid Thu Mar 30 02:27:52 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Mar 2006 07:27:52 GMT Subject: any() and all() on empty list? References: <1143630405.344694.269060@u72g2000cwu.googlegroups.com> Message-ID: Ron Adam wrote: > Where we are assembling widgets in a manufacturing plant. Where we don't > want to go to the next step until *all* the sub parts are present. > > if all(part.status == 'present' for part in unit): > do_release() > > Oops! Some empty bins showed up at the next assembly station. ;-) I don't see the problem. You only get an empty bin if there is some part assembled from no sub-parts, in which case you wanted an empty bin. From dmbkiwi at gmail.com Fri Mar 3 13:39:03 2006 From: dmbkiwi at gmail.com (dmbkiwi at gmail.com) Date: 3 Mar 2006 10:39:03 -0800 Subject: PyQt issue Message-ID: <1141411143.575922.296190@p10g2000cwp.googlegroups.com> I'm trying to write a simple dialog with PyQt. Ive got this code as one of the slots: def setFixed(self): if len(str(self.fixed_label.displayText())) == 0: QMessageBox.critical(self, "Label Missing", "You must enter a label.") else: print str(self.fixed_date_month.currentText()) print str(self.fixed_date_day.currentText()) day_text = str(self.fixed_date_day.curentText()) + ' ' + str(self.fixed_date_month.currentText()) self.date_list.insertItem(date_text) self.label_list.insertItem(str(self.fixed_label.displayText())) When run, the output is: January 1 Traceback (most recent call last): File "/home/matt/karamba/date_calc/date_config.py", line 285, in setFixed day_text = str(self.fixed_date_day.curentText()) + ' ' + str(self.fixed_date_month.currentText()) AttributeError: curentText How can it print .currentText(), but then throw an AttributeError when I try an put them in a variable? Any help appreciated. Cheers Matt From jstroud at ucla.edu Mon Mar 27 22:10:03 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 27 Mar 2006 19:10:03 -0800 Subject: what is the the best way to express following: In-Reply-To: References: <_uOdnaBMCLmcPLXZRVn-uA@comcast.com> Message-ID: AndyL wrote: > James Stroud wrote: > >> Here is a suggestion >> >> todo = {(int, long):abc, (str,):afg, (tuple, list):ijk} >> todo[type(key)]() > > > > Is not that a shortcut? I have got "KeyError" exception ... No, I hit send too soon, mixing ideas in my head. Paul McGuire's answer is the way to go. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From http Thu Mar 30 18:20:24 2006 From: http (Paul Rubin) Date: 30 Mar 2006 15:20:24 -0800 Subject: any() and all() on empty list? References: <442B9AF7.2010407@REMOVEMEcyber.com.au> <7xu09gicko.fsf@ruckus.brouhaha.com> <442BAAA5.8010009@REMOVEMEcyber.com.au> <7xwtebpw95.fsf@ruckus.brouhaha.com> Message-ID: <7x64lvfrk7.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > >> No, all(seq) is true if every element in seq is true. Surely that's a > >> more intuitive definition than your definition by what you can't do. > > They are different? > Of course they are different -- they differ in the case of an empty > sequence. I don't think they differ in the case of an empty sequence. If the sequence is empty, both statements are true. > > By the definition, "all flying elephants are pink" and "all flying > > elephants are non-pink" are both true statements, if that's what > > you're asking. There is no contradiction. > > Of course there is a contradiction. The contradiction is that flying > elephants are simultaneously pink and not pink. Neither statement asserts the existence of any flying elephants regardless of color, so neither statement contradicts the other statement. > If you don't understand why "Foo is Bar" and "Foo is not Bar" can't both > be true simultaneously, I suggest you spend some time googling on > "noncontradiction logic". To get you started, here's the Wikipedia entry: > > http://en.wikipedia.org/wiki/Law_of_noncontradiction "All flying elephants are pink" is not a statement of the form "Foo is Bar". See , as I've cited several times. "All flying elephants are pink" simply means "there are no non-pink flying elephants". "All flying elephants are non-pink" similarly means "there are no pink flying elephants". The statements don't contradict, and in fact both statements are true. > if husband.stopped_beating_wife(): # returns True or False > pay_fine() > else: > go_to_jail() > > Pretty hard on the innocent husbands who never even beat their wife at all. Correct. The code should not be written that way. > In hacker culture, the Chinese word > "mu" (literally "without") is sometimes used to mean "I cannot answer that > question because your assumptions are not correct". > > In the case of all(seq), the correct answer is "mu". I don't think it's that bad. We just have to spell out precisely what the assumptions are, and we've done so. From trepca at gmail.com Thu Mar 30 12:56:41 2006 From: trepca at gmail.com (Sebastjan Trepca) Date: Thu, 30 Mar 2006 19:56:41 +0200 Subject: Very stupid question. In-Reply-To: References: <1143739683.410001.118730@t31g2000cwb.googlegroups.com> <1143740072.340188.281730@i40g2000cwc.googlegroups.com> Message-ID: On 3/30/06, Sullivan Zheng wrote: > > Wow, seems I am not that supid. Why python does not include this function > in the file object. It is almost a tradition in other languages... > > import os > > os.stat(path).st_size > > really not elegant or OO. > > True. -- Sebastjan http://www.trepca.si/blog -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr._bogus_.com Sun Mar 5 17:02:41 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 05 Mar 2006 22:02:41 GMT Subject: Separating elements from a list according to preceding element References: <1141587629.918414.245530@t39g2000cwt.googlegroups.com> Message-ID: <5eJOf.20990$n%2.9299@tornado.texas.rr.com> "Rob Cowie" wrote in message news:1141587629.918414.245530 at t39g2000cwt.googlegroups.com... > I'm having a bit of trouble with this so any help would be gratefully > recieved... > > After splitting up a url I have a string of the form > 'tag1+tag2+tag3-tag4', or '-tag1-tag2' etc. The first tag will only be > preceeded by an operator if it is a '-', if it is preceded by nothing, > '+' is to be assumed. > > Using re.split, I can generate a list that looks thus: > ['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4'] > > I wish to derive two lists - each containing either tags to be > included, or tags to be excluded. My idea was to take an element, > examine what element precedes it and accordingly, insert it into the > relevant list. However, I have not been successful. > > Is there a better way that I have not considered? If this method is > suitable, how might I implement it? > > Thanks all, > > Rob Cowie > Here's how this would look with pyparsing (download pyparsing at http://pyparsing.sourceforge.net ): data = 'tag1+tag2+tag3-tag4' from pyparsing import * tag = Word(alphas,alphanums) incl = Literal("+").suppress() excl = Literal("-").suppress() inclQual = Optional(incl) + tag exclQual = excl + tag qualDef = OneOrMore( inclQual.setResultsName("includes",listAllMatches=True ) | exclQual.setResultsName("excludes",listAllMatches=True ) ) quals = qualDef.parseString(data) print quals.includes print quals.excludes Prints out: [['tag1'], ['tag2'], ['tag3']] [['tag4']] -- Paul From ziga.seilnacht at gmail.com Fri Mar 24 07:30:04 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 24 Mar 2006 04:30:04 -0800 Subject: Strange metaclass behaviour References: <1143127358.820526.259930@i40g2000cwc.googlegroups.com> <1143138624.25186@news.aic.at> <1143188732.510491.233900@t31g2000cwb.googlegroups.com> Message-ID: <1143203404.329141.194770@z34g2000cwc.googlegroups.com> Michele Simionato wrote: There is a minor bug in your code: > def thisclass(proc, *args, **kw): > """ Example: > >>> def register(cls): print 'registered' > ... > >>> class C: > ... thisclass(register) > ... > registered > """ > # basic idea stolen from zope.interface, which credits P.J. Eby > frame = sys._getframe(1) > assert '__module__' in frame.f_locals # <----------------------------------- here > def makecls(name, bases, dic): > try: > cls = type(name, bases, dic) > except TypeError, e: > if "can't have only classic bases" in str(e): > cls = type(name, bases + (object,), dic) > else: # other strange errors, such as __slots__ conflicts, etc > raise > del cls.__metaclass__ > proc(cls, *args, **kw) > return cls > frame.f_locals["__metaclass__"] = makecls > > Figured you would like this one ;) > > Michele Simionato See this example: >>> import sys >>> def in_class_statement1(): ... frame = sys._getframe(1) ... return '__module__' in frame.f_locals ... >>> def in_class_statement2(): ... frame = sys._getframe(1) ... return '__module__' in frame.f_locals and not \ ... '__module__' in frame.f_code.co_varnames ... >>> class A(object): ... print in_class_statement1() ... print in_class_statement2() ... True True >>> def f(): ... __module__ = 1 ... print in_class_statement1() ... print in_class_statement2() ... >>> f() True False From peter.j.bismuti at boeing.com Thu Mar 16 15:07:58 2006 From: peter.j.bismuti at boeing.com (Peter J. Bismuti) Date: Thu, 16 Mar 2006 12:07:58 -0800 Subject: accessing attributes when inheriting? Message-ID: <200603161207.58215.peter.j.bismuti@boeing.com> How do you access attributes of a class when inheriting from it? Can't you just say: self.attribute? Help?! ....................................................................................................... #!/usr/bin/python from Dialog import Dialog import enscmd class RatDialog(Dialog): def __init__(self,parent = Dialog,name = "RatDialog",modal = 0,fl = 0): Dialog.__init__(self) self.ClipListView.header().setLabel(0,self.__tr("Clips")) <----ERROR self.ClipListView.clear() def CloseButton_clicked(self): self.close() .................................................................................... from qt import * class Dialog(QDialog): def __init__(self,parent = None,name = None,modal = 0,fl = 0): QDialog.__init__(self,parent,name,modal,fl) if not name: self.setName("Dialog") DialogLayout = QGridLayout(self,1,1,11,6,"DialogLayout") layout14 = QVBoxLayout(None,0,6,"layout14") layout13 = QHBoxLayout(None,0,6,"layout13") self.ClipListView = QListView(self,"ClipListView") self.ClipListView.addColumn(self.__tr("Column 1")) layout13.addWidget(self.ClipListView) self.ClipTextEdit = QTextEdit(self,"ClipTextEdit") layout13.addWidget(self.ClipTextEdit) layout14.addLayout(layout13) layout10 = QHBoxLayout(None,0,6,"layout10") layout9 = QVBoxLayout(None,0,6,"layout9") layoutWidth = QHBoxLayout(None,0,6,"layoutWidth") self.WidthLabel = QLabel(self,"WidthLabel") layoutWidth.addWidget(self.WidthLabel) self.WidthLineEdit = QLineEdit(self,"WidthLineEdit") layoutWidth.addWidget(self.WidthLineEdit) layout9.addLayout(layoutWidth) layout5 = QVBoxLayout(None,0,6,"layout5") self.OriginLabel = QLabel(self,"OriginLabel") self.OriginLabel.setAlignment(QLabel.WordBreak | QLabel.AlignCenter) layout5.addWidget(self.OriginLabel) layoutX = QHBoxLayout(None,0,6,"layoutX") self.XLabel = QLabel(self,"XLabel") layoutX.addWidget(self.XLabel) self.XLineEdit = QLineEdit(self,"XLineEdit") layoutX.addWidget(self.XLineEdit) layout5.addLayout(layoutX) layoutY = QHBoxLayout(None,0,6,"layoutY") self.YLabel = QLabel(self,"YLabel") layoutY.addWidget(self.YLabel) self.YLineEdit = QLineEdit(self,"YLineEdit") layoutY.addWidget(self.YLineEdit) layout5.addLayout(layoutY) layoutZ = QHBoxLayout(None,0,6,"layoutZ") self.ZLabel = QLabel(self,"ZLabel") layoutZ.addWidget(self.ZLabel) self.ZLineEdit = QLineEdit(self,"ZLineEdit") layoutZ.addWidget(self.ZLineEdit) layout5.addLayout(layoutZ) layout9.addLayout(layout5) layout10.addLayout(layout9) self.ButtonGroup = QButtonGroup(self,"ButtonGroup") self.CircleRadioButton = QRadioButton(self.ButtonGroup,"CircleRadioButton") self.CircleRadioButton.setGeometry(QRect(20,50,56,21)) self.SquareRadioButton = QRadioButton(self.ButtonGroup,"SquareRadioButton") self.SquareRadioButton.setGeometry(QRect(20,20,64,21)) self.SquareRadioButton.setChecked(1) layout10.addWidget(self.ButtonGroup) layout14.addLayout(layout10) layout11 = QHBoxLayout(None,0,6,"layout11") self.NewClipButton = QPushButton(self,"NewClipButton") layout11.addWidget(self.NewClipButton) self.DeleteClipButton = QPushButton(self,"DeleteClipButton") layout11.addWidget(self.DeleteClipButton) self.CloseButton = QPushButton(self,"CloseButton") layout11.addWidget(self.CloseButton) layout14.addLayout(layout11) DialogLayout.addLayout(layout14,0,0) self.languageChange() self.resize(QSize(340,427).expandedTo(self.minimumSizeHint())) self.clearWState(Qt.WState_Polished) self.connect(self.NewClipButton,SIGNAL("clicked()"),self.NewClipButton_clicked) self.connect(self.DeleteClipButton,SIGNAL("clicked()"),self.DeleteClipButton_clicked) self.connect(self.CloseButton,SIGNAL("clicked()"),self.CloseButton_clicked) def languageChange(self): self.setCaption(self.__tr("RAT")) self.ClipListView.header().setLabel(0,self.__tr("Column 1")) self.ClipListView.clear() item = QListViewItem(self.ClipListView,None) item.setText(0,self.__tr("New Item")) self.WidthLabel.setText(self.__tr("Width/Radius")) self.OriginLabel.setText(self.__tr("Origin")) self.XLabel.setText(self.__tr("X")) self.YLabel.setText(self.__tr("Y")) self.ZLabel.setText(self.__tr("Z")) self.ButtonGroup.setTitle(self.__tr("Clip Type")) self.CircleRadioButton.setText(self.__tr("Circle")) self.SquareRadioButton.setText(self.__tr("Square")) self.NewClipButton.setText(self.__tr("New")) self.DeleteClipButton.setText(self.__tr("Delete")) self.CloseButton.setText(self.__tr("Close")) def NewClipButton_clicked(self): print "Dialog.NewClipButton_clicked(): Not implemented yet" def DeleteClipButton_clicked(self): print "Dialog.DeleteClipButton_clicked(): Not implemented yet" def CloseButton_clicked(self): print "Dialog.CloseButton_clicked(): Not implemented yet" def __tr(self,s,c = None): return qApp From pmartin at snakecard.com Sun Mar 26 13:07:32 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sun, 26 Mar 2006 12:07:32 -0600 Subject: image reduction script References: <%cUUf.2478$fS6.24@dukeread11><44241E0D.80605@websafe.com> <1143353989.469397.41690@j33g2000cwa.googlegroups.com> Message-ID: Kamilche, I am posting the code in another thread but am not certain that convert does anything to the picture color depth ... still searching in the doc. Philippe Kamilche wrote: > > To reduce the color depth of an image in PIL: > im = im.convert(mode="P", palette=Image.ADAPTIVE) From sybrenUSE at YOURthirdtower.com.imagination Tue Mar 28 06:56:50 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 28 Mar 2006 13:56:50 +0200 Subject: Converting Time question References: Message-ID: Math enlightened us with: > How do I convert a time of day from milliseconds? Milliseconds since what? 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 Mar 21 12:36:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 21 Mar 2006 18:36:38 +0100 Subject: Can XML-RPC performance be improved? References: Message-ID: Sion Arrowsmith wrote: > I've got an established client-server application here where there > is now a need to shovel huge amounts of data (structured as lists of > lists) between the two, and the performance bottleneck has become > the amount of time spent parsing XML (it's taking 100% CPU on one or > other end of the connection and accounting for well over 50% of the > total call time, to the extent that it's having a greater impact on > performance than user interaction). And this is using SGMLOP for > parsing -- I dread to think what it would be like with a slower > parser. Anyone (Fredrik?) got any good ideas for tackling this > problem? the cElementTree unmarshaller on this page http://effbot.org/zone/element-iterparse.htm#incremental-decoding is a bit faster than the one in xmlrpclib. (to get more performance, you probably need a library that allows you to register decoders on the C level.) From scott.daniels at acm.org Fri Mar 31 18:10:11 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 31 Mar 2006 15:10:11 -0800 Subject: Find similar images using python In-Reply-To: References: <1143637570.842988.44030@z34g2000cwc.googlegroups.com> Message-ID: <442db42e$1@nntp0.pdx.net> Christos Georgiou wrote: > .... I did make a module based on imgseek, and together with PIL, > I manage my archive of email attachments (it's incredible how many > different versions of the same picture people send you: gif, jpg > in different sizes etc) and it works fairly well. > > E-mail me if you want the module, I don't think I have it currently online > anywhere. This sounds like a great recipe for the cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python -- -Scott David Daniels scott.daniels at acm.org From escalation746 at yahoo.com Mon Mar 13 21:44:15 2006 From: escalation746 at yahoo.com (robin) Date: Tue, 14 Mar 2006 02:44:15 +0000 Subject: New python.org website References: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> <1141737431.437281.178860@z34g2000cwc.googlegroups.com> <1141757397.508448.296600@e56g2000cwe.googlegroups.com> Message-ID: "Michael Tobis" wrote: >While the new one is much better than the old website, the logo strikes >me as awful. I personally believe the new logo is miles better than the old one. Whether you see snakes or a plus-sign or a yin-yang, it has a nice harmonious look that still captures some playfulness. Besides, why is everyone fixated on snakes? Python the language has nothing to do with python the constrictor. As far as the layout goes, I still find it too busy. Specifically there are too many fonts on the one page. But I have already made that point, and did an entire version of the homepage, which the team have taken as input. Anyone who has the time can do the same, rather than simply comment from the sidelines. The best websites never stay still, but are constantly evolving. I hope python.org can do the same, and go from strength to strength. Congratulations to all involved! ----- robin noisetheatre.blogspot.com From tchur at optushome.com.au Fri Mar 10 16:07:23 2006 From: tchur at optushome.com.au (Tim Churches) Date: Sat, 11 Mar 2006 08:07:23 +1100 Subject: Python Evangelism In-Reply-To: <1213apcnisvatb9@corp.supernews.com> References: <1142005777.058808.198630@e56g2000cwe.googlegroups.com> <1213apcnisvatb9@corp.supernews.com> Message-ID: <4411EA8B.8070007@optushome.com.au> Benny wrote: > Paul Boddie wrote: > >> Bizarre names may be cute (to some people) but they don't lend >> themselves to guessing or searching. Consequently, people who want >> answers yesterday aren't likely to be amused to eventually discover >> that the name of the resource they've been looking for is some opaque, >> three-levels-of-indirection-via-irony, in-crowd joke. And even acronyms >> like CPAN are better than wacky names, anyway. > > To emphasize the point as a newbie: I know what CPAN is. I would go to > the Vaults of Parnassus for Python stuff. But Cheese Shop? I like the irony of the name Cheese Shop, but I do think that there is a problem with "Shop", as it typically means a place where you buy things for money. However, the vast majority of the cheesy comestibles at the Cheese Shop are available for free. In fact, of 1287 packages currently listed there, only 7 have non-free or proprietary licenses. Actually, it was the "National Cheese Emporium" in the original sketch, although Mr Wensleydale does describe it as a cheese shop - but both "shop" and "emporium" are used to describe places of commerce. On re-acquaintance, the sketch itself is still very funny after all these years, except perhaps for the ending, in which Mousebender shoots dead Mr Wensleydale for deliberately wasting his time. In the early 1970s in Britain, when shooters were possessed by a very small minority of blaggards, that might have been funny, but in the early 21st century, I find it grates a little (no pun intended) - I can imagine the same fate befalling a latter-day Wensleydale in a different country who happens to be fresh out of meira. But I am sure ESR would defend Mousebender's right to blow poor Wensleydale away - see http://www.catb.org/~esr/guns/gun-ethics.html . So is there an alternative Monty Python sketch which has a theme of purveyance as opposed to commerce? None spring to mind. Tim C From rtilley at vt.edu Thu Mar 9 10:03:40 2006 From: rtilley at vt.edu (rtilley) Date: Thu, 09 Mar 2006 10:03:40 -0500 Subject: Python Evangelism In-Reply-To: References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> Message-ID: Dale Strickland-Clark wrote: > rtilley wrote: > > >>Psychology is important. Just as important as good design. I think this >>fact doesn't sink in to the Python community. > > > You speak of fluff and ribbons and glitter. Yes, I know. Great products, ideas and methods have lost mind share to lesser things (not that Ruby is inferior to Python or vice versa) because they lack fluff, ribbons and glitter :) I hope Python gets more fluff... it already has lost of great technical merit :) From laurent.pointal at limsi.fr Wed Mar 8 03:46:18 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 08 Mar 2006 09:46:18 +0100 Subject: Send email notification In-Reply-To: <1141759889.952367.59260@j33g2000cwa.googlegroups.com> References: <1141759889.952367.59260@j33g2000cwa.googlegroups.com> Message-ID: Ernesto a ?crit : > Is there a special module for mail ? > > I'd like to send an email [to 'n' unique email addresses] from a python > script. If you want all adressee to be the only one visible in to: field, you must send n emails. For such a purpose, see iMailer module here: http://nojhan.free.fr/article.php3?id_article=22 Else, see other posts. A+ Laurent. From johnjsal at NOSPAMgmail.com Sun Mar 26 12:54:50 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 26 Mar 2006 12:54:50 -0500 Subject: is mysqlsb compatible with MySQL 5.0? In-Reply-To: References: <1143322764.631997.10900@v46g2000cwv.googlegroups.com> <1143329611.401677.317190@i40g2000cwc.googlegroups.com> <44260673$0$4001$c3e8da3@news.astraweb.com> <44262519$0$4182$c3e8da3@news.astraweb.com> Message-ID: <4426d5b0$0$19258$c3e8da3@news.astraweb.com> Dennis Lee Bieber wrote: > Check the Windows services control for MySQL and try from it... How do I do that? > > You might (since it sounds like this is a first attempt) need to > uninstall everything -- and make sure you delete the mysql database (in > case you have a garbaged root login) Ugh, if this is the case, is there more to uninstall than just using the Add/Remove programs? Where do I delete the database? From lycka at carmen.se Mon Mar 20 05:00:21 2006 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 20 Mar 2006 11:00:21 +0100 Subject: Need design advice. What's my best approach for storing this data? In-Reply-To: <1142615283.733346.74260@i40g2000cwc.googlegroups.com> References: <1142615283.733346.74260@i40g2000cwc.googlegroups.com> Message-ID: Mudcat wrote: > I am trying to build a tool that analyzes stock data. Therefore I am > going to download and store quite a vast amount of it. Just for a > general number - assuming there are about 7000 listed stocks on the two > major markets plus some extras, 255 tradying days a year for 20 years, > that is about 36 million entries. > > Obviously a database is a logical choice for that. However I've never > used one, nor do I know what benefits I would get from using one. I am > worried about speed, memory usage, and disk space. This is a typical use case for relational database systems. With something like DB2 or Oracle here, you can take advantage of more than 20 years of work by lots of developers trying to solve the kind of problems you will run into. You haven't really stated all the facts to decide what product to choose though. Will this be a multi-user applications? Do you forsee a client/server application? What operating system(s) do you need to support? With relational databases, it's plausible to move some of the hard work in the data analysis into the server. Using this well means that you need to learn a bit about how relational databases work, but I think it's with the trouble. It could mean that much less data ever needs to reach your Python program for processing, and that will mean a lot for your performance. Relational databases are very good at searching, sorting and simple aggregations of data. SQL is a declarative language, and in principle, your SQL code will just declare the correct queries and manipulations that you want to achieve, and tuning will be a separate activity, which doesn't need to involve program changes. In reality, there are certainly cases where changes in SQL code will influence performance, but to a very large extent, you can achieve good performance through building indices and by letting the database gather statistics and analyze the queries your programs contain. As a bonus, you also have advanced systems for security, transactional safety, on- line backup, replication etc. You don't get these advantages with any other data storage systems. I'd get Chris Fehily's "SQL Visual Quickstart Guide", which is as good as his Python book. As database, it depends a bit on your platform you work with. I'd avoid MySQL. Some friends of mine have used it for needs similar to yours, and they are now running into its severe shortcomings. (I did warn them.) For Windows, I think the single user version of SQL Server (MSDE?) is gratis. For both Windows and Linux/Unix, there are (I think) gratis versions of both Oracle 10g, IBM DB2 UDB and Mimer SQL. Mimer SQL is easy to install, Oracle is a pain, and I think DB2 is somewhere in between. PostgreSQL is also a good option. Either way, it certainly seems natural to learn relational databases and SQL if you want to work with financial software. From g.brandl-nospam at gmx.net Tue Mar 28 09:52:39 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Tue, 28 Mar 2006 16:52:39 +0200 Subject: 1.090516455488E9 / 1000000.000 ??? In-Reply-To: References: Message-ID: <48t0tnFlqr5gU1@individual.net> Math wrote: > Hello, > > I got a simple and probably stupid newby question.. > When I compute: > 1.090516455488E9 / 1000000 > the result is 1090516455.49 > Should be 1090516455.488 > > I know something with float and //... > > Anybody? > How do I get correct number? Python 2.4.2 (#1, Mar 12 2006, 00:14:41) [GCC 3.4.5 (Gentoo 3.4.5-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 1.090516455488E15 / 1000000 1090516455.4879999 >>> print 1.090516455488E15 / 1000000 1090516455.49 print is using str() which formats the float number with 12 digits precision and therefore rounds the result. repr() however, which is used by the interpreter when printing out expression results, uses 17 digits precision which is why you can see how the result is stored in the computer's memory (1090516455.487999999999999....). Georg From piton123 at yahoo.com Wed Mar 8 09:38:46 2006 From: piton123 at yahoo.com (Bob Piton) Date: 8 Mar 2006 14:38:46 -0000 Subject: Basic Python FTP Question References: <1141805374.698398.228500@j52g2000cwj.googlegroups.com> Message-ID: On Wed, 08 Mar 2006 00:09:34 -0800, Ravi Teja wrote: > Have you seen Python's ftplib? > http://effbot.org/librarybook/ftplib.htm > http://docs.python.org/lib/module-ftplib.html No I hadn't. Thanks for the references; it looks like that method will do anything I need to do with ftp. From jstroud at ucla.edu Sat Mar 11 17:36:05 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 11 Mar 2006 14:36:05 -0800 Subject: How to refer to the function object itself in the function per se? In-Reply-To: <1142110896.395475.211630@z34g2000cwc.googlegroups.com> References: <1142108608.559879.45560@i39g2000cwa.googlegroups.com> <1142110896.395475.211630@z34g2000cwc.googlegroups.com> Message-ID: Sullivan WxPyQtKinter wrote: If I would like to refer to the function object in order > to call it recursively, what shall I do then? I think the question is too simple. You can just refer to the function by its name. Here is an example: py> def f(start, end): ... if start >= end: ... print 'start is end:', start ... else: ... print "start increasing to:", start ... f(start+1, end) ... print 'leaving f() where start is', start ... py> f(1,10) start increasing to: 1 start increasing to: 2 start increasing to: 3 start increasing to: 4 start increasing to: 5 start increasing to: 6 start increasing to: 7 start increasing to: 8 start increasing to: 9 start is end: 10 leaving f() where start is 10 leaving f() where start is 9 leaving f() where start is 8 leaving f() where start is 7 leaving f() where start is 6 leaving f() where start is 5 leaving f() where start is 4 leaving f() where start is 3 leaving f() where start is 2 leaving f() where start is 1 James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From ruby at no.spam Sat Mar 11 18:11:22 2006 From: ruby at no.spam (Michal Kwiatkowski) Date: Sun, 12 Mar 2006 00:11:22 +0100 Subject: Why property works only for objects? In-Reply-To: <1hc1fgy.5nq08nvj7qkaN%aleaxit@yahoo.com> References: <1hbyfgj.a3p39r1smomavN%aleaxit@yahoo.com> <4412107a$0$22499$636a55ce@news.free.fr> <1hbzzh7.1qlkv8hokpiqzN%aleaxit@yahoo.com> <1hc1abj.1fokrj9826uvjN%aleaxit@yahoo.com> <1hc1fgy.5nq08nvj7qkaN%aleaxit@yahoo.com> Message-ID: Alex Martelli napisa?(a): >> It still bugs me. What's the actual procedure when doing attribute >> assignment? I understand it like this: >> >> obj.attr = value >> * if instance class has __setattr__, call it >> * else: if class has an attribute with name "attr" check if it's a >> descriptor; when it's overriding descriptor, call its __set__ >> method, otherwise raise AttributeError >> * else: bind "attr" as object attribute > > Yes, this is correct. Can you also check my reasoning for getting attributes? value = obj.attr * if instance class has __getattribute__, call it * else: lookup "attr" in all parent classes using class __mro__; if it's a descriptor call its __get__ method, return its value otherwise (when descriptor doesn't have __get__, it's unreadable and AttributeError is raised) * else: check instance __dict__ for "attr", return it when found * else: lookup __getattr__ in instance class and call it when found * else: raise AttributeError > Opening a bug report on the Python bugtracker would maximize the > likelihood that something gets done about this bug. Bug submitted: http://sourceforge.net/tracker/index.php?func=detail&aid=1448042&group_id=5470&atid=105470 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 700MHz at gmail.com Fri Mar 31 04:12:23 2006 From: 700MHz at gmail.com (LUK) Date: 31 Mar 2006 01:12:23 -0800 Subject: Can I control Video Card by using Python under linux? Message-ID: <1143796342.957617.147690@i40g2000cwc.googlegroups.com> Hi, I have a video card based on cx2388 chip to catch video and do the other thing. There's already a V4L2 driver for it, but it is too hard for me to program in C. Can I use Python do the job? Does Python has simpler APIs? Please gvie me some suggestion. Thanks! From replaceafill at yahoo.com Thu Mar 30 18:10:44 2006 From: replaceafill at yahoo.com (Douglas Douglas) Date: Thu, 30 Mar 2006 15:10:44 -0800 (PST) Subject: Identifying filled circles in a scanned image Message-ID: <20060330231044.66670.qmail@web34203.mail.mud.yahoo.com> Hi everybody. I have a paper form that I scan into an image. My user fills some circles in this paper form using black ink. Every form has ten rows with five circles each and the user fills only one circle for each row. I was wondering if I could use the Python Imaging Library to process these forms. I know the Image class is really powerful, but I can't think of a way of how to locate wich circle was filled. Could anybody please give me an advice on this? Thanks. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From johnjsal at NOSPAMgmail.com Thu Mar 30 10:21:03 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 30 Mar 2006 15:21:03 GMT Subject: a hobbyist's dilemma In-Reply-To: <122nqan6hrb579a@corp.supernews.com> References: <122nqan6hrb579a@corp.supernews.com> Message-ID: Benny wrote: > John Salerno wrote: > >> Anyway, any suggestions are appreciated! > > What've you got for hobbies? Hmm, my hobbies...well, programming for one. :) Also literature and anything computer-related. I suppose I could try to catalog some books. One like I'd like to learn is how to use Python with MySQL, but I just can't get MySQL to work on my computer, so I'm at a dead end there. Seems like the best option for cataloging though. From kadeko at gmail.com Mon Mar 27 09:35:59 2006 From: kadeko at gmail.com (looping) Date: 27 Mar 2006 06:35:59 -0800 Subject: XMLRPCServer issues In-Reply-To: References: <1143454964.071222.304540@e56g2000cwe.googlegroups.com> <1143467008.869965.50360@g10g2000cwb.googlegroups.com> Message-ID: <1143470159.016742.139210@e56g2000cwe.googlegroups.com> Fredrik Lundh wrote: > "looping" wrote: > > > > 2. You might want to transmit integers as strings rather than use the > > > XML-RPC integer type (which is limited to numbers between -2147483648 > > > and 2147483647). > > > > Is it a limit of XML-RPC RFC or a limit (probably with a good reason) > > of the python xmlrpclib ? > > the specification defines an integer field as a "four-byte signed integer". > > OK, I will remove my MAXINT hack and convert value to string. Thanks everybody for your fast answers, nice group with nice (and brillant) people. See you later for my next question. From just at xs4all.nl Thu Mar 9 05:23:38 2006 From: just at xs4all.nl (Just) Date: Thu, 09 Mar 2006 11:23:38 +0100 Subject: Python Evangelism References: Message-ID: In article , Steve Holden wrote: > I've been thinking (and blogging) about python evangelism since PyCon, > as a result of which I created a squidoo lens: > > http://www.squidoo.com/pythonlogy > > Imagine my surprise at discovering that this has gone up in rank (by > number of views) from # 442,000 or so to #153! Clearly there's some > mileage in marketing Python, and I'd like to keep the buzz going if it > means more people will adopt the language. > > Any suggestions for improvement? Yeah, the URL: http://www.squidoo.com/pythonology :) Just From peter.maas at somewhere.com Mon Mar 6 16:40:12 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Mon, 06 Mar 2006 22:40:12 +0100 Subject: Python advocacy in scientific computation In-Reply-To: References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> <1141583453.403143.189400@i40g2000cwc.googlegroups.com> <1141589892.094037.18410@i40g2000cwc.googlegroups.com> Message-ID: Steve Holden schrieb: > sturlamolden wrote: >> First there are a few things I don't like: >> >> 1. Intendation as a part of the syntax, really annoying. >> > Troll. You think this is going away because *you* don't like it? You are over-reacting. Keep in mind that sturlamolden has criticized Python and not you :) I think there is a more convincing reply to indentation phobia: It is natural that compiler and programmer agree on how to identify block structures. Anybody who disagrees should bang his code against the left side or put everything in one line to get rid of annoying line breaks. :) Peter Maas, AAchen From exhuma at gmail.com Mon Mar 20 03:38:18 2006 From: exhuma at gmail.com (exhuma.twn) Date: 20 Mar 2006 00:38:18 -0800 Subject: combining mod_python handlers publisher and psp problem Message-ID: <1142843898.023725.73070@i39g2000cwa.googlegroups.com> Simple problem: When I define a funtion the way you would with the publisher handler (without using psp), all works as expected. However when I define a publisher-like function and instantiate a PSP object in it ( as suggested on http://www.onlamp.com/pub/a/python/2004/02/26/python_server_pages.html ) mod_python seems to fail to tell the browser which content-type the document has. The output is what I expect it to be, but instead of rendering the page I see the source code, so I suppose the browser sees it as "text/python" or "text/plain". I tried to do a print "Content-Type: text/html" print as first statement, but then it only outputs that as normal text too. Any ideas? From kent at kentsjohnson.com Tue Mar 28 11:42:13 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 28 Mar 2006 11:42:13 -0500 Subject: Seems like I want a pre-processor, but... In-Reply-To: <1143562487.421862.258860@u72g2000cwu.googlegroups.com> References: <1143562487.421862.258860@u72g2000cwu.googlegroups.com> Message-ID: <44296235$1_3@newspeer2.tds.net> Russell Warren wrote: > After some digging it seems that python does not have any equivalent to > C's #if directives, and I don't get it... > > For example, I've got a bit of python 2.3 code that uses > collections.deque.pop(0) in order to pop the leftmost item. In python > 2.4 this is no longer valid - there is no argument on pop (rightmost > only now) and you call .popleft() instead. > > I would like my code to work in both versions for now and simply want > to add code like: > > if sys.version[:3] == "2.3": > return self.myDeque.pop(0) > else: > return self.myDeque.popleft() Often you can make these tests one-time by defining an appropriate object whose value depends on the test, then using that object instead of repeatedly making the test. In this case, I assume the code above is inside a class method. You could have the class conditionally define a myPopLeft() method like this (not tested): class MyClass(object): ... if sys.version[:3] == "2.3": def myPopLeft(self): return self.myDeque.pop(0) else: def myPopLeft(self): return self.myDeque.popleft() Now the class has a myPopLeft() method that does the right thing, and sys.version is only tested once, at class declaration time. You might want to make the condition explicitly on the deque class, also, using has_attr(deque, 'popleft'). Another example is the common code used to define 'set' portably across Python 2.3 and 2.4: try: set except NameError: from sets import Set as set In general the idea is to move the test from 'every time I need to do something' to 'once when some name is defined'. Kent From bearophileHUGS at lycos.com Mon Mar 6 18:51:26 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Mar 2006 15:51:26 -0800 Subject: IronPython on Shootout In-Reply-To: <1141687168.885590.315980@z34g2000cwc.googlegroups.com> References: <1141681481.219194.178320@j52g2000cwj.googlegroups.com> <1141687168.885590.315980@z34g2000cwc.googlegroups.com> Message-ID: <1141689086.340414.16280@j33g2000cwa.googlegroups.com> This is the answer that I did receive about Boo: https://alioth.debian.org/tracker/index.php?func=detail&aid=302999&group_id=30402&atid=411005 igouy-guest>We already have languages no one uses and no one writes rograms for - once there are a bunch of shootout programs written in Boo and tested on Mono...< It seems that no enough people are willing to write Boo programs for the Shootout. If you want to write many of them then igouy can probably put Boo back... Bye, bearophile From peter at engcorp.com Thu Mar 30 13:39:40 2006 From: peter at engcorp.com (Peter Hansen) Date: Thu, 30 Mar 2006 13:39:40 -0500 Subject: Very stupid question. In-Reply-To: References: <1143739683.410001.118730@t31g2000cwb.googlegroups.com> <1143740072.340188.281730@i40g2000cwc.googlegroups.com> Message-ID: On 3/30/06, *Sullivan Zheng* > wrote: > > Wow, seems I am not that supid. Why python does not include this > function in the file object. It is almost a tradition in other > languages... > > import os > > os.stat(path).st_size > > really not elegant or OO. You might find something like Jason Orendorff's path.py module (Google for it) to be more elegant. With it, this works fine: >>> from path import path >>> path('foobar').getsize() 12345L (But note that it's just a nice wrapper around the scattered builtin ways of doing the same thing, in this case the os.stat().st_size approach mentioned above. That's not a bad thing, though, IMHO.) -Peter From reply.in.the.newsgroup at my.address.is.invalid Wed Mar 15 17:22:19 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 15 Mar 2006 23:22:19 +0100 Subject: Python compiler References: Message-ID: Rc: >My question is where can I find a compiler for free. >For Windows XP. http://www.python.org/download/ -- Ren? Pijlman From johnjsal at NOSPAMgmail.com Wed Mar 8 23:20:14 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Mar 2006 23:20:14 -0500 Subject: advice on this little script In-Reply-To: References: <2bSdncqWK7aJN5LZRVn-vA@rcn.net> Message-ID: James Stroud wrote: > Very nice, but maybe > > ... > sleep(60.0) > > This corrects for the number of seconds in a minute. > > James > Thanks! And yeah, I fixed that little issue. If only laundry could be done that fast. :) From mkluwe at gmail.com Thu Mar 9 10:47:24 2006 From: mkluwe at gmail.com (Matthias Kluwe) Date: 9 Mar 2006 07:47:24 -0800 Subject: StaticBoxSizer problems References: <1141848308.410869.90390@z34g2000cwc.googlegroups.com> Message-ID: <1141919244.683761.21050@j33g2000cwa.googlegroups.com> Hi! > Matthias Kluwe wrote: >> I'd like to place several StaticBoxes in a frame, but I can't get it >> right. >> Consider the following code: > >> import wx > >> app = wx.PySimpleApp() >> frame = wx.Frame(parent=None, title="Test") >> box = wx.BoxSizer(wx.VERTICAL) >> frame.SetSizer(box) >> upper_box = wx.StaticBox(parent=frame, label="Upper Box") >> box.Add(item=upper_box, flag=wx.GROW) > > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > > You should remiove this line. Hmm. As I see it, this means constructing the StaticBox and not placing it in the frame. Obviously, this does not help. > [...] > >> What am I missing? > > Generally speaking what you appear to be missing is a methodical > approach to GUI consruction. This reminds me of a lot of my early > experiments with wxPython code :-) "a methodical approach to GUI construction"? Please be more specific -- any hints are welcome. Clearly, the above is an experiment with wxPython, not anything methodical. This may follow when I understand how StaticBoxSizer works. Regards, Matthias From bencvt at gmail.com Wed Mar 15 19:51:39 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 15 Mar 2006 16:51:39 -0800 Subject: "pow" (power) function In-Reply-To: <1142465999.800332.73050@i39g2000cwa.googlegroups.com> References: <1142465999.800332.73050@i39g2000cwa.googlegroups.com> Message-ID: <1142470299.753531.269360@j52g2000cwj.googlegroups.com> Russ wrote: > I have a couple of questions for the number crunchers out there: Sure, but the answers depend on the underlying Python implementation. And if we're talking CPython, they also depend on the underlying C implementation of libm (i.e., math.h). > Does "pow(x,2)" simply square x, or does it first compute logarithms > (as would be necessary if the exponent were not an integer)? The former, using binary exponentiation (quite fast), assuming x is an int or long. If x is a float, Python coerces the 2 to 2.0, and CPython's float_pow() function is called. This function calls libm's pow(), which in turn uses logarithms. > Does "x**0.5" use the same algorithm as "sqrt(x)", or does it use some > other (perhaps less efficient) algorithm based on logarithms? The latter, and that algorithm is libm's pow(). Except for a few special cases that Python handles, all floating point exponentation is left to libm. Checking to see if the exponent is 0.5 is not one of those special cases. If you're curious, download the Python source, open up Objects/floatobject.c, and check out float_pow(). The binary exponentation algorithms are in Objects/intobject:int_pow() and Objects/longobject:long_pow(). The 0.5 special check (and any other special case optimizations) could, in theory, be performed in the platform's libm. I'm not familiar enough with any libm implementations to comment on whether this is ever done, or if it's even worth doing... though I suspect that the 0.5 case is not. Hope that helps, --Ben From python at rcn.com Sun Mar 12 11:18:23 2006 From: python at rcn.com (Raymond Hettinger) Date: 12 Mar 2006 08:18:23 -0800 Subject: time series calculation in list comprehension? In-Reply-To: References: <1142012049.892323.103060@v46g2000cwv.googlegroups.com> <1142022950.378619.103360@e56g2000cwe.googlegroups.com> Message-ID: <1142180303.789670.276420@i40g2000cwc.googlegroups.com> [Peter Otten] > from __future__ import division > > from itertools import islice, tee, izip . . . > def moving_average2(items, n): > first_items, last_items = tee(items) > accu = sum(islice(last_items, n-1)) > for first, last in izip(first_items, last_items): > accu += last > yield accu/n > accu -= first > > While moving_average1() is even slower than your inefficient variant, > moving_average2() seems to be a tad faster than the efficient one. This is nicely done and scales-up well. Given an n-average of m-items, it has O(n) memory consumption and O(m) running time. In contrast, the other variants do more work than necessary by pulling the whole sequence into memory or by re-summing all n items at every step, resulting in O(m) memory consumption and O(m*n) running time. This recipe gets my vote for the best solution. Raymond From deets at nospam.web.de Thu Mar 23 05:26:24 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 23 Mar 2006 11:26:24 +0100 Subject: Probelem about image size and dimensions References: <1143109000.672508.175070@t31g2000cwb.googlegroups.com> Message-ID: <48fbg4Fjqn9hU1@uni-berlin.de> gongcheng_g at hotmail.com wrote: > I got a piece of python script to upload file and it can upload it to > different folders on server depend on the type of file is image or not. > but I also want to restrict the size and dimensions of file if it is a > image file.Could anyone help me out? Use PIL, the python imaging library. Load your image, check its sizes and proceed accordingly. Diez From arkanes at gmail.com Thu Mar 2 16:33:57 2006 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 2 Mar 2006 15:33:57 -0600 Subject: wxPython memory footprint? - Re: Write a GUI for a python script? In-Reply-To: References: <1141315236.636933.149430@i39g2000cwa.googlegroups.com> Message-ID: <4866bea60603021333m38ff2897nd94284744249ece0@mail.gmail.com> On 3/2/06, robert wrote: > ianar? wrote: > > > wxPython is another good option, especially since there is > > boa-constructor, which is a great GUI builder, almost makes it too easy > > to make a nice looking app in no time at all. > > > > http://www.wxpython.org/download.php > > > > http://boa-constructor.sourceforge.net/ > > > > if you decide to give wxPython a go, make sure to download the demo, it > > has tons of usefull code samples. > > What is the minimal memory footprint of a Hello World wxPython app > meanwhile (when you cx_freeze/py2exe it) ? > I'm assuming you mean disk space and not memory usage. A stock wxPython (from a standard release) wil vary from platform to platform but is generally about 2.5 megs. This can be brought down rather a lot if you're willing to spend a fair amount of time learning the wxWidgets and wxPython build systems and making custom builds but it's not generally worth the time to me (and I know the build system and could make customized builds if I wanted to) I have a non-trivial wxPython application and, using py2exe in "single executable" mode (thus all the dlls and the zipfile with the .pyc files are included in the exe) it's just over 5 megs in size. > Can you debug & call functions interactively from e.g. Pythonwin while a > wxPython app is running. > I've never tried it with PythonWin and I don't know how PythonWin hooks into Python to manage debugging). Both pdb and the debugger in PyDev work fine for me, however. As another responder said it's trivial (literally < 5 lines) to add an interactive Python shell to a wxPython application, which is invaluable for debugging and testing. > ( When I made a test with wxPython some years ago, it had no option to > step/share its Messageloop. Interaction was "crust"y and I didn't manage > to get smooth debugging (on Windows). ) > I don't believe that wxPython exposes the low level C++ APIs that're available to hook the wx message loop (it's an efficency issue, from what I understand), but there are a number of other methods for integration. The need to hook the message loop is far far less common than the number of people who ask for it, so you'll forgive me if I'm skeptical unless someone actually says why they want to. > Robert > -- > http://mail.python.org/mailman/listinfo/python-list > From steven.bethard at gmail.com Wed Mar 1 10:32:20 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 01 Mar 2006 08:32:20 -0700 Subject: Make staticmethod objects callable? In-Reply-To: <44055BE0.8030409@REMOVEMEcyber.com.au> References: <44055BE0.8030409@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > So, based on this evidence, staticmethod() inside a class definition > converts instance methods to functions. Outside a class definition, > staticmethod() does one of two things: it either converts an instance > method to a static method, or if the output is assigned to a class > attribute, it leaves it as an instance method. This is exactly why I'm concerned about augmenting staticmethod's behavior. When people run into this, it should be the opportunity to explain to them how descriptors work. Descriptors are hugely important in the new object system, and even if we hide them by giving staticmethod a __call__, we'll still run into problems when people try to do: class C(object): @classmethod def foo(cls): print cls bar = foo(None) Then, not only do we have to explain how descriptors work, but we also have to explain why staticmethod has a __call__, and classmethod doesn't. (For anyone else out there reading who doesn't already know this, Steven D'Aprano's comments are easily explained by noting that the __get__ method of staticmethod objects returns functions, and classes always call the __get__ methods of descriptors when those descriptors are class attributes: >>> class C(object): ... @staticmethod ... def foo(): ... pass ... print foo ... >>> print C.foo >>> @staticmethod ... def foo(): ... pass ... >>> print foo >>> print foo.__get__(C, None) Yes, you have to explain descriptors, but at the point that you start trying to do funny things with staticmethods and classmethods, I think you need to start learning about them anyway.) All that said, you should probably just submit a patch and see what happens. I'll make a brief comment on it along the above lines, but since I'm not a committer, it's not really worth your time to try to convince me. ;) STeVe From webraviteja at gmail.com Thu Mar 16 15:59:50 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 16 Mar 2006 12:59:50 -0800 Subject: Binary python extensions with Free Pascal Compiler In-Reply-To: <1142542143.010853.208920@z34g2000cwc.googlegroups.com> References: <1142542143.010853.208920@z34g2000cwc.googlegroups.com> Message-ID: <1142542790.828105.76070@i40g2000cwc.googlegroups.com> I posted this a few days ago. According to the website (http://mmm-experts.com/VersionHistory.aspx?ProductId=3), FPC support has been added since version 3.29. From paraic.gallagher at gmail.com Wed Mar 22 10:40:33 2006 From: paraic.gallagher at gmail.com (Paraic Gallagher) Date: Wed, 22 Mar 2006 15:40:33 +0000 Subject: Default/editable string to raw_input In-Reply-To: <1143040181.462433.64130@u72g2000cwu.googlegroups.com> References: <1143040181.462433.64130@u72g2000cwu.googlegroups.com> Message-ID: <44216FF1.1060506@gmail.com> David Wahler wrote: >With the disclaimer that, as others have said, this may not be the best >user-interface choice: > > import readline > readline.set_startup_hook(lambda: readline.insert_text(old_value)) > try: > new_value = raw_input() > finally: > readline.set_startup_hook(None) > >Note that, among other issues, this isn't threadsafe (but then, you >really shouldn't be doing console I/O from multiple threads anyway). >Hope this helps. > >-- David > > > Thanks David, this was exactly what I was looking for. Paraic. From workbee at gmail.com Wed Mar 15 13:03:46 2006 From: workbee at gmail.com (Enigma Curry) Date: 15 Mar 2006 10:03:46 -0800 Subject: Threads: does Thread.start() atomically set Thread.__started ? In-Reply-To: References: <1142377158.896072.310710@u72g2000cwu.googlegroups.com> Message-ID: <1142445826.500349.319470@j52g2000cwj.googlegroups.com> Peter, Thanks for the reference! I don't know why but for some reason I thought that I would be wading through a bunch of C code (which I know very little of). I haven't found my answer yet but this threading.py does look fairly straightforward. Thanks! From roy at panix.com Sat Mar 18 14:43:02 2006 From: roy at panix.com (Roy Smith) Date: Sat, 18 Mar 2006 14:43:02 -0500 Subject: ipv6 validation References: <1142705173.912345.301840@g10g2000cwb.googlegroups.com> Message-ID: In article <1142705173.912345.301840 at g10g2000cwb.googlegroups.com>, jiri.juranek at kctdata.cz wrote: > Hello, > is there any common function for validation if string contains valid ip > address(both ipv4 and ipv6)? Or does sb wrote some regular expression > for this? > thanks > J Look at socket.inet_pton(). First check to make sure ipv6 is supported on your platform, then pass your string to inet_pton() inside of a try block to catch socket.error. It would have been nicer is a more specific exception was thrown, but this seems to work. For example: >>> socket.has_ipv6 True >>> socket.inet_pton(socket.AF_INET6, "8001::1244") '\x80\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x12D' >>> socket.inet_pton(socket.AF_INET6, "8001:xyz:1244") Traceback (most recent call last): File "", line 1, in ? socket.error: illegal IP address string passed to inet_pton >>> Be aware that IPv6 support is messy on Windows. For example, if you're running Win 2003 (or XP, I would guess), the OS does support IPv6 (and thus socket.has_ipv6 will probably bet set to True) but the IPv6 libraries don't actually get loaded until you configure an IPv6 address on some interface. This means things like inet_pton() will fail, which is truly bletcherous and evil. Writing a regex to recognize valid IPv6 presentation strings is not trivial. Keep in mind that you're allowed exactly 0 or 1 "::" occurrances, and things like "ffff::192.168.11.1" are legal (I don't remember if I got the semantics right there, but the syntax is legal). From fuzzyman at gmail.com Fri Mar 31 02:04:14 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 30 Mar 2006 23:04:14 -0800 Subject: [ANN] Firedrop 0.2.1 Message-ID: <1143788654.661485.218950@i40g2000cwc.googlegroups.com> Firedrop 0.2.1 has just been released. http://www.voidspace.org.uk/python/firedrop2/ A bugfix release. * Removed mistaken dependency on `pythonutils `_ * Fixed bug where cancelling the new site dialog would still report that the site was created **Firedrop2** is a cross-platform blogging tool written in `Python `_. It keeps your blog source files on your computer, making it a *clientside* tool. This means you control your blog, and can easily move it from one server to another, with no risk of losing data. It also means you can manage your blog *offline*. It is fully open source, and has all the features you expect from a modern blogging program : * {acro;RSS;Really Simple Syndication} feed generation * Categories * Automatic archive generation * A powerful set of plugins, including spell checker and emailer * Entries can be made in text, {acro;HTML}, {acro;ReST}, textile, sextile or markdown markup * HTML templating system and macros for all sorts of tricks * Built in {acro;FTP} capability for uploading your blog to a server * Because it's written in Python, it is easy to extend Firedrop or create new plugins for it From joel.hedlund at gmail.com Mon Mar 13 05:42:32 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Mon, 13 Mar 2006 11:42:32 +0100 Subject: Python IDE: great headache.... In-Reply-To: References: <1142120002.912902.69630@i40g2000cwc.googlegroups.com> Message-ID: >> Anyone knows if this platform is a good one? It's very good. It's comfortable, helpful and stable. Also looks good. > Eclipse + Pydev does most, if not all, of your list - I am not sure what > you mean by conditional pause - plus a whole lot more. Maybe he means conditional breakpoints? PyDev certainly has that. > I like Eclipse, but lots of folks on the Python groups seem to hate it > with a passion. Any ideas why? > If you install Eclipse and try to use it without reading the Workbench > User Guide then you are not going to get anywhere. Woah, easy now! I never read any "Workbench User Guide" and I'm doing just fine with PyDev. Fabio Zadrozny (PyDev developer) wrote an excellent startup guide for python programmers that includes installing and basic editing: http://www.fabioz.com/pydev/manual_101_root.html It's all I ever read and it was enough for me to get going with Eclipse + PyDev within 15 minutes on a WinXP machine. On a side note: with Ubuntulinux 5.10 it was more of a hassle, but that was just to get Eclipse running smoothly. I.e: an Eclipse/apt/Java problem. Once that was neatly in place, that guide above worked flawlessly. Cheers! /Joel Hedlund From fredrik at pythonware.com Wed Mar 15 12:26:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Mar 2006 18:26:29 +0100 Subject: Queue limitations? References: <1142440071.355627.120450@z34g2000cwc.googlegroups.com> Message-ID: mateom at gmail.com wrote: > I'm using Queue to send images from one thread to another, and some of > the images are not appearing in the consumer thread....maybe 1 in 3 > arrive. I've tried passing the image data in both string form and as a > PIL Image object, with the same result. > > It does work, however, if I use zlib to compress the image string > before passing it to Queue and then decompress it in the consumer > thread. So, my question: Does Queue have some capacity limitation? > (Uncompressed, my images are 786432 long... 512x512x3) the queue holds references to the images, not the images themselves, so the size should be completely irrelevant. > class imageQueue(threading.Thread): > > def __init__(self): > threading.Thread.__init__(self) > self.filenum = 0 > self.theQueue = Queue.Queue(-1) > > def run(self): > while 1: > # for testing, do something simple with images > img = self.theQueue.get() > imgt = Image.frombuffer('RGB',(512,512), img) > #imgt = Image.frombuffer('RGB',(512,512), zlib.decompress(img)) #this one works > imgt.save( "./imgs_out/%i.png" % self.filenum, "PNG") > self.filenum += 1 how many instances of the imageQueue are you using ? From donald.welch at hp.com Tue Mar 28 18:20:21 2006 From: donald.welch at hp.com (dwelch) Date: Tue, 28 Mar 2006 15:20:21 -0800 Subject: A SANE scanner backend written in Python? Message-ID: <4429c4d2$1@usenet01.boi.hp.com> I've read many times on this newsgroup over the years that you can write "just about anything" in Python, except perhaps a full operating system (maybe even that...?). So, with this spirit in mind, I would like to try to write a SANE scanner backend that I need to write, in Python rather than C. This work is being done on Linux using Python 2.4.2. If you are not familar with SANE, and the SANE API, it basically boils down to supplying a libsane-.so shared library that supports a basic C interface. Example sane API calls into a backend are: sane_init(), sane_open(), sane_start(), sane_read() and sane_cancel(). At runtime, a backend is loaded up and its C interface is called to determine what devices are supported by the backend, to set options, and to actually perform a scan. Obviously, this is an example of embedding Python, albiet with a different end result. I have not found any examples in the wild that embed Python in a shared library (vs. a standalone executable). My trials so far have been fruitless. To start with, I simply took an outline of a shared library that defined all the relevant SANE APIs, linked it with SANE and Python, and placed a PyInitialize() in the sane_init() function. This immediately results in a segmentation fault. I'm not sure how to proceed from here. How would a separate .py file be accessed in this way and how would I call "back" into Python code when a C API was called? Is there going to be a problem of maintaining "state" in Python between invocations of the C API? I've also explored using Elmer for this task, but have not had luck so far. Its also not clear to me whether this tool is appropriate for this task. So, what I'd be interested in knowing is whether this is a foolish venture, or if I just have the wrong approach. Any thoughts would be appreciated. Thanks, -Don From kent at kentsjohnson.com Sat Mar 18 22:35:33 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sat, 18 Mar 2006 22:35:33 -0500 Subject: POP3 Mail Download In-Reply-To: References: <7g1p12ttfcf1sd5v9rrggr6ioushs2e1id@4ax.com> Message-ID: <441ccc85_2@newspeer2.tds.net> Bob Piton wrote: > On Sat, 18 Mar 2006 18:34:56 -0500, Kevin F wrote: >>i have no idea what you are hinting at, can you please just tell me what i >>need to change? > > > I know how you feel; it's brutal trying to get elementary information from > this group. You could try the python-tutor list, it tends to give more focused answers to newbie questions than this group, which is pretty newbie-friendly but does have a tendency to veer widely from the original question. > Now if only somebody would tell me, with elementary examples, how you > write to the thing called 'stdout' and how you read from 'stdin'. raw_input() prompts to stdout and reads from stdin. print outputs to stdout: In [53]: print raw_input('What is your name? ') What is your name? Kent Kent or import sys and use sys.stdin and sys.stdout. Kent From roy at panix.com Thu Mar 2 16:38:44 2006 From: roy at panix.com (Roy Smith) Date: Thu, 02 Mar 2006 16:38:44 -0500 Subject: do design patterns still apply with Python? References: <8SINf.1718$No6.40137@news.tufts.edu> Message-ID: In article <8SINf.1718$No6.40137 at news.tufts.edu>, John Salerno wrote: > Since Python does so many things different, especially compared to > compiled and statically typed languages, do most of the basic design > patterns still apply when writing Python code? If I were to read a > design pattern book (such as Head First Design Patterns), could I apply > their Java examples to Python easily enough, or does Python require a > different perspective when applying patterns? Many of the classic design patterns apply just fine to Python, at least in the high-level view. On the other hand, much (most?) of what's in the classic design pattern books is so tied up with ways around C++/Java type bondage, it's difficult to see the forest for the trees. For example, take the most classic of all patterns, Singleton. A typical C++ Singleton treatment will be all about making constructors private and shit like that. None of that carries over to Python. What I would do in Python is have a module-level factory function which caches a single instance of the class to return to the 2nd and subsequent caller and not get my panties in a twist over the fact that some clever programmer could find away around my code and force creation of a second instance. The basic concepts in the pattern books are worth knowing. You just have to be able to tease apart the concepts from the language-specific cruft that so often obfuscates the descriptions. From duncan.booth at invalid.invalid Thu Mar 23 10:26:22 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Mar 2006 15:26:22 GMT Subject: Convert Word .doc to Acrobat .pdf files References: <1143123734.158567.97310@i39g2000cwa.googlegroups.com> Message-ID: kbperry wrote: > Hi all, > > Background: > I need some help. I am trying to streamline a process for one of our > technical writers. He is using Perforce (version control system), and > is constantly changing his word documents, and then converts them to > both .pdf and "Web page" format (to publish to the web). He has a > licensed copy of Adobe Acrobat Professional (7.x). > > Questions: > Does Acrobat Pro, have some way to interface with it command-line (I > tried searching, but couldn't find anything)? Is there any other good > way to script word to pdf conversion? As I remember, Acrobat monitors a directory and converts anything it finds there, so you don't need to script Acrobat at all, just script printing the documents. However, it sounds as though you are talking about running Acrobat on a server and his license probably doesn't permit that. Alternatively use OpenOffice: it will convert word documents to pdf or html and can be scripted in Python. From felipe.lessa at gmail.com Sat Mar 11 17:50:19 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sat, 11 Mar 2006 19:50:19 -0300 Subject: "RuntimeError: dictionary changed ... & Ruby In-Reply-To: References: <1hc13h0.44fct0w8frp9N%aleaxit@yahoo.com> Message-ID: <1142117419.7557.4.camel@kenshin> Em S?b, 2006-03-11 ?s 23:44 +0100, robert escreveu: > > Farwell and best of luck in finding other languages which support > > threads in a way that is more to your liking than Python -- maybe Ruby > > suits you, I don't know for sure though. > > I looked several times on Ruby, but stay with Python. Ruby is featured, > but ill designed. [snip] Oh noes! Another rant of Ruby vs. Python! *Please*, no flamewars! From mike.mazurek at gmail.com Wed Mar 22 05:06:44 2006 From: mike.mazurek at gmail.com (Mike Mazurek) Date: Wed, 22 Mar 2006 05:06:44 -0500 Subject: Importing two module variables and having one clobber the other? In-Reply-To: <1142978749.016857.4130@v46g2000cwv.googlegroups.com> References: <1142971896.080149.144080@v46g2000cwv.googlegroups.com> <1142978749.016857.4130@v46g2000cwv.googlegroups.com> Message-ID: You could wrap your paramter dict in a class instance with something like: class Parameters(object): def __init__(self, parameterDict): self.__dict__ = parameterDict.copy() # NB: copying may not be necissary for your case parms = Parameters(dict(a=1,b=2,c=3)) print parms.a, parms.b, parms.c On 21 Mar 2006 14:05:49 -0800, Joseph Turian wrote: > > > Fredrik Lundh wrote: > > > if you prefer to use a "parameters.value" syntax, you can wrap the > resulting > > dictionary in a class. > > That sounds good. How do I do that? > > > I assume "from" means "beneath" and "getcwd" means "walk" ? > > Actually: > def superdirs(d): > lst = [d] > while d != os.environ["HOME"]: > (d, tl) = os.path.split(d) > lst += [d] > lst.reverse() > return lst > > > Joseph > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhellwig at xs4all.nl Tue Mar 28 09:29:08 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Tue, 28 Mar 2006 16:29:08 +0200 Subject: in-place string reversal In-Reply-To: <1143555308.009412.295250@z34g2000cwc.googlegroups.com> References: <1143554931.104392.187480@i39g2000cwa.googlegroups.com> <1143555308.009412.295250@z34g2000cwc.googlegroups.com> Message-ID: <44294839$0$24373$e4fe514c@news.xs4all.nl> Sathyaish wrote: > And that the "extra-memory" operation I've given above is expensive, I > believe. Is there an efficient way to do it? > If i recall correctly a string is an immutable list. I would do it this way: >>> strTXT = "foo" >>> strREV = strTXT[::-1] >>> strREV 'oof' -- mph From martin at v.loewis.de Wed Mar 22 13:14:09 2006 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Wed, 22 Mar 2006 19:14:09 +0100 Subject: Python vs. Java gzip performance In-Reply-To: <1143028651.6919.2.camel@kenshin> References: <1142610889.512781.69650@j33g2000cwa.googlegroups.com> <441B0920.4060106@v.loewis.de> <1142625842.789743.27510@e56g2000cwe.googlegroups.com> <1142977513.263383.88410@i39g2000cwa.googlegroups.com> <4420909E.3080208@v.loewis.de> <1143028651.6919.2.camel@kenshin> Message-ID: <442193F1.5030409@v.loewis.de> Felipe Almeida Lessa wrote: > def readlines(self, sizehint=None): > if sizehint is None: > return self.read().splitlines(True) > # ... > > Is it okay? Or is there any embedded problem I couldn't see? It's dangerous, if the file is really large - it might exhaust your memory. Such a setting shouldn't be the default. Somebody should research what blocking size works best for zipfiles, and then compare that in performance to "read it all at once". It would be good if the rationale for using at most 100 bytes at a time could be discovered. Regards, Martin From aleaxit at yahoo.com Thu Mar 9 01:42:46 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 8 Mar 2006 22:42:46 -0800 Subject: advice on this little script References: <2bSdncqWK7aJN5LZRVn-vA@rcn.net> <120vb889343kd1@corp.supernews.com> <120vcmf3fgdo7d8@corp.supernews.com> Message-ID: <1hbwju0.i6a32q14lekvtN%aleaxit@yahoo.com> Grant Edwards wrote: ... > > Nice! Cross off another line! I feel like Hemingway. :) > > Was he the one who once apologized to his editor for a story > being so long because he was in a hurry and didn't have time to > make it shorter? Nope, that immortal quote is by Blaise Pascal (also known as a philosopher, a mathematician, and the developer of one of the best early mechanical calculators, as well as for the programming language Niklaus Wirth named after him, and the SI standard unit of pressure, 1 Pa == 1 N per square meter, also named in his honor because he was the first to use a barometer to measure altitude); it's found in his "Lettres Provinciales" (which is not a collection of "real" letters, but rather a philosophical, theological and political polemic cast in epistular form). It's often misattributed to Mark Twain, but this the first time I've heard it associated with Hemingway! Alex From mtobis at gmail.com Wed Mar 29 23:25:00 2006 From: mtobis at gmail.com (Michael Tobis) Date: 29 Mar 2006 20:25:00 -0800 Subject: Seems like I want a pre-processor, but... In-Reply-To: References: <1143562487.421862.258860@u72g2000cwu.googlegroups.com> <1143564849.353889.169680@v46g2000cwv.googlegroups.com> Message-ID: <1143692700.579297.210960@j33g2000cwa.googlegroups.com> Well, Bill Mill and I simultaneously and independently decided to write a preprocessor to strip out the unfortunate "@" decorator syntax. I think we were both aiming at a polemic purpose rather than a practical one, but as time fades it seems less clear what we were simultaneously inspired to achieve. Each of us did a crude pass at it and then on encountering each other's approach realized a truly satisfactory implementation would probably be harder than it was worth... In any case isn't ipython an instance of a useful preprocessor? mt From steven.bethard at gmail.com Wed Mar 1 18:03:25 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 01 Mar 2006 16:03:25 -0700 Subject: why descriptors? (WAS: Make staticmethod objects callable?) Message-ID: Steven Bethard wrote: > (For anyone else out there reading who doesn't already know this, > Steven D'Aprano's comments are easily explained by noting that the > __get__ method of staticmethod objects returns functions, and classes > always call the __get__ methods of descriptors when those descriptors > are class attributes: Steven D'Aprano wrote: > Why all the indirection to implement something which is, conceptually, > the same as an ordinary function? While I wasn't around when descriptors and new-style classes were introduced, my guess is that it's mainly because what you *usually* want when defining a function in a class is for that function to be an instance method. That is, the following code:: class C(object): def foo(self): pass c = C() c.foo() should be much more common than:: class C(object): def foo(): pass C.foo() because the whole point of creating a class is to allow you to create instances. But if ``C.foo`` and ``c.foo`` are just regular functions, then how will ``c.foo()`` get the ``self`` argument? Certainly a normal ``foo()`` shouldn't be inserting a magical ``self`` argument. So *some* indirection has to happen when a function is used in a class. Python's solution to this problem is to introduce descriptors, which are the "something" that classes have to do. All classes invoke __get__ whenever any of their attributes are accessed. With a normal function object, invoking __get__ turns it into an instance method: >>> class C(object): ... pass ... >>> def foo(self): ... pass ... >>> foo >>> foo.__get__(C(), C) > >>> class C(object): ... def foo(self): ... pass ... >>> C().foo > As a result, if you want to have a callable as a class attribute and you don't want that callable to give you an instance method when you access it, you can't use a regular Python function. Personally, I think that's pretty reasonable since 99% of the time, I *do* want an instance method[1]. STeVe [1] The other 1% of the time, I pretty much always want a classmethod. I'm still convinced that staticmethods are basically silly when I can just declare a module level function. ;) From scott.daniels at acm.org Wed Mar 15 12:38:23 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 15 Mar 2006 09:38:23 -0800 Subject: Markov process representation Message-ID: <44184edf$1@nntp0.pdx.net> Here's one way (convert each set of transition percentages to a running sum up to one): import random class SingleStateMarkov(object): def __init__(self, probabilities, initial=None): self._states = states = sorted(probabilities) self._fromstate = dict([(name, n) for n, name in enumerate(states)]) self._all_states = set(states) self.transition = dict() for name, row in probabilities.iteritems(): self.transition[name] = self.add_transitions(name, row) if initial is None: initial = self._states[0] elif initial not in self._all_states: raise ValueError('Invalid initial state %s' % initial) self.state = initial def add_transitions(self, name, row): if set(row) - self._all_states: raise ValueError('%s: moves to unknown states %s' % ( name, set(row) - self._all_states)) if min(row.values()) < 0: raise ValueError('%s: bad odds for states %s' % (name, [nm for nm,odds in row.iteritems() if odds < 0])) total = float(sum(row.values())) # Sum of the odds. if total <= 0: raise ValueError('%s: No Transitions allowed' % name) running_total = 0. cumulative = [] for name in self._states: running_total += row.get(name, 0.0) cumulative.append(running_total / total) return cumulative def move(self): v = random.random() for index, entry in enumerate(self.transition[self.state]): if v <= entry: break self.state = self._states[index] return self.state class MultiStateMarkov(SingleStateMarkov): def __init__(self, probabilities, initial=None, order=2): if [key for key in probabilities if len(key) != order]: raise ValueError('State keys wrong size: %s' % [key for key in probabilities if len(key) != order]) self._all_states = set() for i in range(order): self._all_states |= set(key[i] for key in probabilities) self._states = states = sorted(self._all_states) self._fromstate = dict([(name, n) for n, name in enumerate(states)]) self.transition = dict() for key, row in probabilities.iteritems(): self.transition[key] = self.add_transitions(key, row) if initial is None: initial = (self._states[0],) * order elif len(initial) != order or set(initial)-self._all_states: raise ValueError('Invalid initial state %s' % initial) self.state = initial def move(self): v = random.random() for index, entry in enumerate(self.transition[self.state]): if v <= entry: break state = self._states[index] self.state = self.state[1:] + (state,) return state c = SingleStateMarkov(dict(A=dict(A=20, B=50, C=30), B=dict(A=35, B=25, C=40), C=dict(A=70, B=14, C=16))) d = MultiStateMarkov(dict([(('A', 'A'), dict(A=15, B=55, C=30)), (('A', 'B'), dict(A=20, B=45, C=35)), (('A', 'C'), dict(A=60, B=30, C=10)), (('B', 'A'), dict(A=35, B=25, C=40)), (('B', 'B'), dict(A=49, B=48, C=3)), (('B', 'C'), dict(A=60, B=20, C=20)), (('C', 'A'), dict(A=5, B=75, C=20)), (('C', 'B'), dict(A=0, B=90, C=10)), (('C', 'C'), dict(A=70, B=14, C=16))])) --Scott David Daniels scott.daniels at acm.org From johnjsal at NOSPAMgmail.com Thu Mar 30 10:47:36 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 30 Mar 2006 15:47:36 GMT Subject: a hobbyist's dilemma In-Reply-To: <1143732966.418068.226750@e56g2000cwe.googlegroups.com> References: <122nqan6hrb579a@corp.supernews.com> <1143732966.418068.226750@e56g2000cwe.googlegroups.com> Message-ID: benchline wrote: > Since you want to learn to use python with a database you may want to > try it with SQLite. SQLite is a very easy to use database that stores > the whole database in one file. Working with it would be very similar > to working with Mysql through python. > > http://www.sqlite.org > http://initd.org/tracker/pysqlite > The thing about mysql is that it's also the db used on my website, so I figure it might be nice to learn that one in case I ever need to use that db also. Unless the basic uses for all databases are the same (i.e. if it isn't like learning a new language for each different database) From aleaxit at yahoo.com Sun Mar 26 20:39:03 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Mar 2006 17:39:03 -0800 Subject: Python float representation error? References: <1143416404.380648.181190@t31g2000cwb.googlegroups.com> Message-ID: <1hctib6.bk0tl21924m19N%aleaxit@yahoo.com> mailpitches at email.com wrote: > try running this in python: > > print [39.95] > > the output i get is: > [39.950000000000003] > > what's up with that? Why not start by reading the Python online tutorial? Specifically ? Alex From maxm at mxm.dk Wed Mar 22 02:56:06 2006 From: maxm at mxm.dk (Max M) Date: Wed, 22 Mar 2006 08:56:06 +0100 Subject: doctest, unittest, or if __name__='__main__' In-Reply-To: <1142977320.983856.179630@g10g2000cwb.googlegroups.com> References: <1142974528.143287.326360@e56g2000cwe.googlegroups.com> <1142977320.983856.179630@g10g2000cwb.googlegroups.com> Message-ID: <442102da$0$38714$edfadb0f@dread12.news.tele.dk> john_sips_tea at yahoo.com wrote: >>and you can kill two birds with one stone. > > > By that, do you mean you can write your tests and your > docstrings in one shot with doctest? Exactly. >>> '\n'.join(['Doctests are absolutely brilliant!'] * 100) They combine two brilliant ideas that are hard to do in practice. "Testing" and "Literate Programming" In the process it even manages to make both a lot easier. -- 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 eder at tttech.com Thu Mar 23 10:25:13 2006 From: eder at tttech.com (Christian Eder) Date: Thu, 23 Mar 2006 16:25:13 +0100 Subject: Strange metaclass behaviour References: <1143124255.694225.213000@j33g2000cwa.googlegroups.com> Message-ID: Ziga Seilnacht wrote: > I hope that above explanation helps. > Thanks for your support. I now understand what happens here, but I'm not really happy with the situation. Your solution is a nice workaround, but in a quite huge and complex class framework with a lot a custom metaclasses you don't want this code in each __new__ function. And in fact each __new__ which does not contain this fix-code (and which is not completely side-effect free) might break if someone adds additional classes deeps down in the inheritance hierarchy (which is exactly what happened for me). And this is clearly not what one should expect in context of multiple inheritance and cooperative supercalls. Raising a "metatype conflict among bases" error might be a perfectly acceptable behavior here (though it would be better if python resolves the conflict as your code does), but double-executing code is not in my humble opinion. Is this worth a bug-report on sourceforge ? regards chris From sjuranic at gmail.com Tue Mar 28 15:32:55 2006 From: sjuranic at gmail.com (Steve Juranich) Date: Tue, 28 Mar 2006 13:32:55 -0700 Subject: Looking for a language/framework References: <1143559444.045808.38790@u72g2000cwu.googlegroups.com> <1143573777.704126.281830@t31g2000cwb.googlegroups.com> Message-ID: akameswaran at gmail.com wrote: > As far as hosting, I also know > where Zope/Plone hosting from 7.95 a month - although the host doesn't > list it on their ads, they do use and host it. Which host would this be? I'm currently exploring some options for getting a Zope site hosted. Thanks much. -- Steve Juranich Tucson, AZ USA From fumanchu at amor.org Sat Mar 11 15:27:39 2006 From: fumanchu at amor.org (fumanchu) Date: 11 Mar 2006 12:27:39 -0800 Subject: Help Create Good Data Model References: <1142107183.358685.266440@i39g2000cwa.googlegroups.com> Message-ID: <1142108858.951407.27100@p10g2000cwp.googlegroups.com> There's nothing really *broken* jumping out at me. The last three methods (set_value, set_data, and clear_data) probably don't need a mutex, since they will each have their own frame, and the operations are atomic. If that makes no sense, Google for "Python GIL" ;). If you just returned a value from the dict instead of using copy, the same might be said for the get methods--it depends on whether you're storing mutable objects in self.data or not. When you're done with the exercise and want to persist those values somewhere, give Dejavu a try: http://projects.amor.org/dejavu/ Robert Brewer System Architect Amor Ministries fumanchu at amor.org From bignose+hates-spam at benfinney.id.au Sat Mar 25 19:19:36 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 26 Mar 2006 10:19:36 +1000 Subject: Accessing func_name from inside a function References: <1143309619.566327.173640@j33g2000cwa.googlegroups.com> Message-ID: <87k6ainjl3.fsf@rose.polar.local> "James Thiele" writes: > I'd like to access the name of a function from inside the function. A function, like most other objects in Python, can have any number of names bound to it without the object being informed. Any of those names can then be used to reference the object, and the object has no way of knowing by what name it was referenced. Because of this fallacy, it's generally considered bad programming style to want to know "the" name of the current object from inside that object. What is it you're trying to achieve? -- \ "Unix is an operating system, OS/2 is half an operating system, | `\ Windows is a shell, and DOS is a boot partition virus." -- | _o__) Peter H. Coffin | Ben Finney From http Tue Mar 21 01:43:01 2006 From: http (Paul Rubin) Date: 20 Mar 2006 22:43:01 -0800 Subject: Pycrypto - active ?? References: <1142804398.710230.117640@j33g2000cwa.googlegroups.com> <1142807299.141313.306980@i40g2000cwc.googlegroups.com> <1142841321.980154.320340@u72g2000cwu.googlegroups.com> <7xslpdl7yg.fsf@ruckus.brouhaha.com> <1142856119.461122.293150@i40g2000cwc.googlegroups.com> <1142861008.662593.172900@t31g2000cwb.googlegroups.com> <1hchm5b.1vgq264sk3olaN%aleaxit@yahoo.com> <1142919313.863978.133190@i40g2000cwc.googlegroups.com> <7xbqw0bap6.fsf@ruckus.brouhaha.com> <1142921996.314941.175860@j33g2000cwa.googlegroups.com> Message-ID: <7x7j6ob8ne.fsf@ruckus.brouhaha.com> "Frank Millman" writes: > > TLSLite is so far not really a complete SSL implementation by itself. > > It doesn't know how to properly check the signatures on certificate > > chains. It has to use an external module like m2crypto for that. > > When you say "It has to ...", do you mean that TLSLite will do this > automatically if m2crypto is installed, or is it up to me to call the > m2crypto functions to perform this check? I don't remember exactly; see the TLSLite docs. I have the vague memory that you have to specify what kind of checking you want, and if you say you want the cert chain checked, then TLSLite raises an exception if the external lib isn't there. But I'm not sure. From onurb at xiludom.gro Thu Mar 30 09:54:48 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 30 Mar 2006 16:54:48 +0200 Subject: How to determine an object is "scriptable" In-Reply-To: <1143728317.535829.121950@i39g2000cwa.googlegroups.com> References: <1143726903.153135.317880@j33g2000cwa.googlegroups.com> <1143728317.535829.121950@i39g2000cwa.googlegroups.com> Message-ID: <442bf17a$0$493$626a54ce@news.free.fr> abcd wrote: > Richard Brodie wrote: > >>subscriptable: supports an indexing operator, like a list does. > > doesn't seem to be a builtin function or module... It's not. Look no further. > or is that just your > definition of subscriptable? It's a correct definition of 'subscriptable' in the context of the Python programming language - as well as a good exemple of an implied interface. -- 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 totalrekall.co.uk Fri Mar 17 15:30:54 2006 From: john at totalrekall.co.uk (John Dean) Date: Fri, 17 Mar 2006 20:30:54 GMT Subject: Problem with C-API References: <441af112$0$8332$da0feed9@news.zen.co.uk> <480a7gFhgefjU1@uni-berlin.de> Message-ID: <441b1c87$0$8341$da0feed9@news.zen.co.uk> Hi Duncan's example worked to a point. The line PyRun_String( "print x", Py_file_input, dict, dict); print out the contents of x, but I don't want to print x out. I want to be able to grab whateven the variable x contains so that I can pass it on for further processing by the C++ application. BTW this is only a test case. The real scripts are much bigger. I must say the documentation is not of much help and there are no books or articles covering embedding Python in any detail. What there is is very much out of date. -- Best Regards John From olsongt at verizon.net Wed Mar 29 14:47:38 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 29 Mar 2006 11:47:38 -0800 Subject: Validating Syntax only with PyParser_SimpleParseString ? In-Reply-To: <1143637397.818081.11110@g10g2000cwb.googlegroups.com> References: <1143637397.818081.11110@g10g2000cwb.googlegroups.com> Message-ID: <1143661658.516729.155080@i40g2000cwc.googlegroups.com> gaston.gloesener at web.de wrote: > I am seeking for a method to parse single lines of Python code (infact > they are only formulas, so I generate a line like RESULT=). I > do only want to know if the syntax is correct and if there is an error > best would be to know where. > > I did find PyParser_SimpleParseString which does return a node > structure. If there is an error it seems to return NULL, while I did > not find this documented. > > Th eproblem with this is that first I do not get th elopcation of the > syntax error, and second I don't know what is the proper method to free > the node structure after I got it, since I will not use it. Or is there > any better method doing this anyway. > > Environment: Windows / Borland C++ The builtin function compile will throw a SyntaxError if the syntax is bad. >>> compile("1=a","","single") Traceback (most recent call last): File "", line 1, in ? SyntaxError: can't assign to literal >>> From fuzzyman at gmail.com Mon Mar 27 07:42:24 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 27 Mar 2006 04:42:24 -0800 Subject: New development windows, IronPython or PythonWin In-Reply-To: <1143463140.766449.236920@t31g2000cwb.googlegroups.com> References: <1143135013.513865.103820@u72g2000cwu.googlegroups.com> <1143166004.664604.207250@j33g2000cwa.googlegroups.com> <1143412667.007028.308810@i39g2000cwa.googlegroups.com> <1143463140.766449.236920@t31g2000cwb.googlegroups.com> Message-ID: <1143463344.579898.152890@z34g2000cwc.googlegroups.com> Dan wrote: > Thanks to all, my main concern about anything Microsoft picks up and > runs with is that they vear off just slightly from the "standard" and > freeze everyone else out like they have done with their browser, > javascript etc.. etc... etc... So for now I will try to use Python / > PythonWin with the COM support. Dan I shouldn't think that Jim Hugunin will divert from the standard. In fact he's even been asking on Python-Dev whether they should replicate the bugs in Python 2.4 or stick with the documented behaviour ! Jim is in charge of the project and was the lead developer behind Jython - so he literally knows Python inside out. Anyway - PythoNWin and COM may well be the right approach for your problem anyway. :-) Fuzzyman http://www.voidspace.org.uk/python/index.shtml From jzgoda at o2.usun.pl Wed Mar 1 14:19:13 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 01 Mar 2006 20:19:13 +0100 Subject: Thread Question In-Reply-To: References: <1141155072.500444.215130@v46g2000cwv.googlegroups.com> <4404b15a_3@newspeer2.tds.net> Message-ID: Just napisa?(a): > I always felt that subclassing Thread is very unpythonic. It seems like > an unfortunate leftover Javaism (much of threading.py was inspired by > Java, but I don't need to tell you that). If I need some state, I create > my own class, with a reference to the Thread object if needed. Has-a vs. > is-a. For me, it's not a "javaism", but "delphism" (since I know Delphi/ObjectPascal much better than Java). In fact, in most OO languages I know, threads are modeled as classes. Followning common practice in this matter makes sense when you program in many languages - your threads will be always classes with similar repertoire of methods and attributes. -- Jarek Zgoda http://jpa.berlios.de/ From mforbes at lnsDOTmit.edu Sun Mar 5 02:07:12 2006 From: mforbes at lnsDOTmit.edu (Michael McNeil Forbes) Date: Sat, 4 Mar 2006 23:07:12 -0800 Subject: how to overload sqrt in a module? In-Reply-To: References: Message-ID: On Fri, 3 Mar 2006, Steven D'Aprano wrote: > ... you can do this: > > import my_module > my_module.set_environment("math") # or cmath, or numeric, or whatever > > Your my_module will be like this: > > # Warning: untested code. > ENVIRON = None # global variables sometimes have their uses > > def f(x): > if ENVIRON is None: > raise ValueError("Uninitialised module!") > # or use a custom exception > return ENVIRON.sqrt(x) > > def set_environment(name): > global ENVIRON > ENVIRON = __import__(name) > > > Does this help? Yes. However, this raises a question: Is this any different than directly modifying the globals, or is it just syntactic sugar. import math as my_math def set_environment(name): globals()['ENVIRON'] = __import__(name) Thanks, Michael. From dthierbach at usenet.arcornews.de Thu Mar 23 08:43:26 2006 From: dthierbach at usenet.arcornews.de (Dirk Thierbach) Date: Thu, 23 Mar 2006 14:43:26 +0100 Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1143024937.827420.104100@i39g2000cwa.googlegroups.com> <20060322141400.1A00.1.NOFFLE@dthierbach.news.arcor.de> <1143110872.284192.325230@u72g2000cwu.googlegroups.com> Message-ID: <20060323134326.C29.0.NOFFLE@dthierbach.news.arcor.de> Dinko Tenev wrote: > Dirk Thierbach wrote: >> If more time during preprocessing is allowed, another idea is to >> treat the wildcard expressions as regular expressions, convert >> each into a finite state machine, construct the "intersection" of >> all these state machines, minimize it and then swap final and non-final >> states. > Given the requirements, did you mean taking the *union* and swapping > states? Or maybe swapping states first, and then taking the > intersection? Whatever the requirements were. Take your pick. :-) >> Then you can use the resulting automaton to efficiently >> enumerate S^n - W. In the above case, the resulting FSM would have just >> three states. > I don't see immediately how exactly this is going to work. Unless I'm > very much mistaken, a FSA in the classical sense will accept or reject > only after the whole sequence has been consumed, and this spells > exponential times. Exponential in respect to what? You just recursively walk the automaton for every word of length n, so at most you'll have to check every word in S^n once. Hence, the complexity is not worse than the "generate and test" approach (it's in fact better, since testing is trivial). However, if the result set is simple (as in the example), then the result FSM will have states that won't have transitions for every letters, so I guess the average case will be a lot better. > For improved asymptotic complexity in this case, > you need to be able to at least reject in mid-sequence, One can do that if there is no valid transition out of some state. I guess one could even optimize on that: In the minimal automaton, every state has some transition sequence that will end up in a final state. Annotate each state with the minimum number of steps for such a sequence. While walking the automaton, keep the maximum number of letters to produce in a variable. If this number is small then the number in the annotation, stop and backtrace. This should guarantee that only those states are visited that really produce some output. - Dirk From beyerxyzzy at acm.org Thu Mar 9 14:52:18 2006 From: beyerxyzzy at acm.org (Hugh Beyer) Date: Thu, 09 Mar 2006 19:52:18 GMT Subject: Pythong CGI scrips on Windows Server 2003 Message-ID: We are moving to a new server running Windows Server 2003 from existing servers runing Windows Server 2002 and IIS is giving us fits. Apparently, the IUSR_* accounts are now used to run scripts and they are not by default given the necessary rights. We gave this account the necessary rights "Adjust memory quotas for a process" and "replace a process level token", and that didn't help. So we used the adsutil IIS admin script to set CreateProcessAsUser to false. Now PERL SCRIPTS WORK, but Python scripts still do not. Does anyone have any idea what to look for next? Anyone seen this before? Hugh From wkehowski at cox.net Wed Mar 22 17:32:16 2006 From: wkehowski at cox.net (wkehowski at cox.net) Date: 22 Mar 2006 14:32:16 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: <20060322141400.1A00.1.NOFFLE@dthierbach.news.arcor.de> References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1143024937.827420.104100@i39g2000cwa.googlegroups.com> <20060322141400.1A00.1.NOFFLE@dthierbach.news.arcor.de> Message-ID: <1143066736.857495.203350@i40g2000cwc.googlegroups.com> "And it doesn't really matter what language you use to implement this algorithm, it's the idea that counts. Notation aside, all implementations will be quite similar." I'll guess I'll get out my Turing tape. ;) What are some good references for finite state machines? Minimization? From robert.kern at gmail.com Wed Mar 15 12:53:00 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 15 Mar 2006 11:53:00 -0600 Subject: Getting started with Scipy/NumPy In-Reply-To: <1142444302.364289.210130@j52g2000cwj.googlegroups.com> References: <1142444302.364289.210130@j52g2000cwj.googlegroups.com> Message-ID: tkpmep at hotmail.com wrote: > I installed SciPy and NumPy (0.9.5, because 0.9.6 does not work with > the current version of SciPy), and had some teething troubles. I looked > around for help and observed that the tutorial is dated October 2004, > and is not as thorough as Python's documentation. Is there an > alternative source of information that lists all the functions and > their usage? http://www.scipy.org/doc/api_docs/ > I tried using scipy.info to get information on the std function in the > stats libary, and ran into the following problem. > >>>>x = [1, 2, 3, 4] >>>>import scipy >>>>scipy.std(x) > > 1.2909944487358056 > >>>>scipy.info(std) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > scipy.info(std) > NameError: name 'std' is not defined You would need to do scipy.info(scipy.std) >>>>scipy.info(stats) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > scipy.info(stats) > NameError: name 'stats' is not defined > >>>>scipy.info(stats.std) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > scipy.info(stats.std) > NameError: name 'stats' is not defined > > However, If I redo the import as follows I can get help on std: > >>>>from scipy import * >>>>info(std) > > std(a, axis=0, dtype=None) > > None > > Question: why did it work this time and not on my first attempt? Because you did a different kind of import on the second attempt. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From martin at v.loewis.de Fri Mar 10 16:58:45 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 10 Mar 2006 22:58:45 +0100 Subject: XML international characters In-Reply-To: References: Message-ID: <4411f695$0$31226$9b622d9e@news.freenet.de> Andreas R. wrote: > When parsing XML documents containing international characters, such as > the Norwegian characters ?, ?, ?, I get an exception in Python's SAX > module. What is the correct way to parse such characters in Python? I've > searched for methods to somehow escape the characters, without any luck > so far. The correct way is to provide correct XML. If you get a parse error, it really means that there is an error in your XML file. Most likely, the encoding of the characters is inconsistent with the declared encoding. Notice that the default encoding of XML (in absence of a declaration) is UTF-8. Regards, Martin From fabianosidler at gmail.com Tue Mar 28 13:58:13 2006 From: fabianosidler at gmail.com (Fabiano Sidler) Date: Tue, 28 Mar 2006 20:58:13 +0200 Subject: Why are so many built-in types inheritable? In-Reply-To: References: <441c6498$1_1@news.cybercity.ch> <4424c104_2@newspeer2.tds.net> <1143323897.342734.63080@u72g2000cwu.googlegroups.com> Message-ID: I really wanted to learn the reason for this, nothing else! ;) Greetings, F. Sidler From nick at craig-wood.com Thu Mar 16 03:30:05 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 16 Mar 2006 02:30:05 -0600 Subject: Tried Ruby (or, "what Python *really* needs" or "perldoc!") References: <1142355126.757569.42160@i40g2000cwc.googlegroups.com> <1142397587.151040.35450@j33g2000cwa.googlegroups.com> <1142434139.499666.281590@v46g2000cwv.googlegroups.com> <87wtevv9va.fsf@workhorse.earlhome> Message-ID: Jason Earl wrote: > Why don't you instead install the info version of the Python > documentation on your server. Then you can do "info Python2.3-lib" > and have at it. I didn't know about that. Its very good. Its still not all the documentation for all the installed modules (a-la perltoc) but it is much better than I thought! info on its own reveals these possible info packages for python Python * Python2.3-api: (python2.3-api). Python/C 2.3 API Reference Manual * Python2.3-dist: (python2.3-dist). Distributing Python Modules (2.3) * Python2.3-ext: (python2.3-ext). Extending & Embedding Python 2.3 * Python2.3-lib: (python2.3-lib). Python 2.3 Library Reference * Python2.3-ref: (python2.3-ref). Python 2.3 Reference Manual * Python2.3-tut: (python2.3-tut). Python 2.3 Tutorial -- Nick Craig-Wood -- http://www.craig-wood.com/nick From nospam at nospam.com Thu Mar 9 13:48:29 2006 From: nospam at nospam.com (3c273) Date: Thu, 9 Mar 2006 10:48:29 -0800 Subject: timeit.py examples in docs generate error Message-ID: Hello, I was reading the thread on try/except overhead and decided to try Alex's examples but they kept generating exceptions. So I went to the docs and tried the examples there (copied and pasted) with the same results (Win2k, Python 2.4). Any help is appreciated. The output follows: #1 C:\Python24\Lib>timeit.py 'if hasattr(int, "__nonzero__"): pass' Traceback (most recent call last): File "C:\Python24\Lib\timeit.py", line 285, in ? sys.exit(main()) File "C:\Python24\Lib\timeit.py", line 249, in main t = Timer(stmt, setup, timer) File "C:\Python24\Lib\timeit.py", line 116, in __init__ code = compile(src, dummy_src_name, "exec") File "", line 6 'if ^ SyntaxError: EOL while scanning single-quoted string #2 C:\Python24\Lib>timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass' Traceback (most recent call last): File "C:\Python24\Lib\timeit.py", line 285, in ? sys.exit(main()) File "C:\Python24\Lib\timeit.py", line 249, in main t = Timer(stmt, setup, timer) File "C:\Python24\Lib\timeit.py", line 116, in __init__ code = compile(src, dummy_src_name, "exec") File "", line 7 ' ^ SyntaxError: EOL while scanning single-quoted string Thanks again, Louis From multani at free.fr Sat Mar 18 08:52:51 2006 From: multani at free.fr (Jonathan Ballet) Date: Sat, 18 Mar 2006 14:52:51 +0100 Subject: xmlrpclib and carriagereturn (\r) References: Message-ID: Le Sat, 18 Mar 2006 08:54:49 +0100, Fredrik Lundh a ?crit?: > Jonathan Ballet wrote: > [snip] > > XMLRPC is XML, and XML normalizes line feeds: > > http://www.w3.org/TR/2004/REC-xml-20040204/#sec-line-ends > > relying on non-standard line terminators in text is fragile and horridly out- > dated; if the data you're sending qualifies as text, send it as text, and do > the conversion at the end points (if at all necessary). Ah, you send me the right link. So xmlrpclib handle those line terminators correctly. That's good. > > if it's not text, use the binary wrapper. > >> I send to them only "\n\n", which makes problems when rendering strings. > > how are you rendering things if you have problems treating a line feed > as a line feed? that's rather unusual; most Windows applications have > no problems handling line feeds properly, so I'm not sure why it has to > be a problem in your application... > > The problem recently pointed out, so we were searching where those carriage return disapeared. However, if we can throw them away and render line feed as line feed, it would be the best solution imho. I'll look into this. Thanks for your answer, J. From just at xs4all.nl Sat Mar 18 10:06:03 2006 From: just at xs4all.nl (Just) Date: Sat, 18 Mar 2006 16:06:03 +0100 Subject: Generating exceptions from C References: <441BF396.2090102@gmail.com> Message-ID: In article , Jacob Kroon wrote: > I'll just reply to myself what I've found out so far: > > > 1. PyErr_NewException() creates the exception _class_, not the > > instance right ? > > > Looks like it does yes. It doesn't even seem right to talk about an > _instance_ of an exception... > > > 2. Is PyErr_SetString() the correct way to raise exceptions ? > > After looking at error.c in the python sources, it looks like that > function sets > the global exception type and value variables to the provided arguments. > > > 3. Besides the error message I pass to PyErr_SetString(), I also want > > to pass additional return > > data together with the exception. But this should be attached to the > > exception _instance_, > > not the class, am I right ? > > > The right way seems to be to create a tuple that consists of the string > message, and any additional data, > and pass the tuple in PyErr_SetObject(). > > > 4. If I am supposed to attach it to the exception instance, how would > > I do that ? I never have a > > pointer to the exception instance, just the class. > > As said previously, there is never an instance of the exception, data is > passed in the "value" argument. > > > Does the comments above make sense? Not quite: when raising an exception, an instance of the exception class _is_ created. Just like this: raise SomeException(msg) With the old (deprecated) spelling the instantiation is done implicitly: raise SomeException, msg Just From petr at tpc.cz Wed Mar 29 18:24:58 2006 From: petr at tpc.cz (Petr Jakes) Date: 29 Mar 2006 15:24:58 -0800 Subject: excel application In-Reply-To: <1143644666.914943.121390@i40g2000cwc.googlegroups.com> References: <1143644666.914943.121390@i40g2000cwc.googlegroups.com> Message-ID: <1143674698.625375.46650@e56g2000cwe.googlegroups.com> Luca, you can find a lot of answers to your questions on this discussion group. If you will try to search using key words "excel constants" for example, you will get the link to the following link (among others): http://tinyurl.com/go3qf IMHO it is good idea to search the web and discussion groups before posting questions (I am not saying it is a bad idea to ask here, I am only trying to show an simple alternative how to get an answers to your questions to you) HTH Regards Petr Jakes From jstroud at ucla.edu Thu Mar 16 15:35:37 2006 From: jstroud at ucla.edu (James Stroud) Date: Thu, 16 Mar 2006 12:35:37 -0800 Subject: accessing attributes when inheriting? In-Reply-To: References: Message-ID: Peter J. Bismuti wrote: > > How do you access attributes of a class when inheriting from it? Can't you > just say: > > self.attribute? > > Help?! > ....................................................................................................... > #!/usr/bin/python > > from Dialog import Dialog > import enscmd > > class RatDialog(Dialog): > def __init__(self,parent = Dialog,name = "RatDialog",modal = 0,fl = 0): > Dialog.__init__(self) > self.ClipListView.header().setLabel(0,self.__tr("Clips")) <----ERROR > self.ClipListView.clear() > def CloseButton_clicked(self): > self.close() > > .................................................................................... > > from qt import * > > > class Dialog(QDialog): > def __init__(self,parent = None,name = None,modal = 0,fl = 0): > QDialog.__init__(self,parent,name,modal,fl) > > if not name: > self.setName("Dialog") > > > DialogLayout = QGridLayout(self,1,1,11,6,"DialogLayout") > > layout14 = QVBoxLayout(None,0,6,"layout14") > > layout13 = QHBoxLayout(None,0,6,"layout13") > > self.ClipListView = QListView(self,"ClipListView") > self.ClipListView.addColumn(self.__tr("Column 1")) > layout13.addWidget(self.ClipListView) > > self.ClipTextEdit = QTextEdit(self,"ClipTextEdit") > layout13.addWidget(self.ClipTextEdit) > layout14.addLayout(layout13) > > layout10 = QHBoxLayout(None,0,6,"layout10") > > layout9 = QVBoxLayout(None,0,6,"layout9") > > layoutWidth = QHBoxLayout(None,0,6,"layoutWidth") > > self.WidthLabel = QLabel(self,"WidthLabel") > layoutWidth.addWidget(self.WidthLabel) > > self.WidthLineEdit = QLineEdit(self,"WidthLineEdit") > layoutWidth.addWidget(self.WidthLineEdit) > layout9.addLayout(layoutWidth) > > layout5 = QVBoxLayout(None,0,6,"layout5") > > self.OriginLabel = QLabel(self,"OriginLabel") > self.OriginLabel.setAlignment(QLabel.WordBreak | QLabel.AlignCenter) > layout5.addWidget(self.OriginLabel) > > layoutX = QHBoxLayout(None,0,6,"layoutX") > > self.XLabel = QLabel(self,"XLabel") > layoutX.addWidget(self.XLabel) > > self.XLineEdit = QLineEdit(self,"XLineEdit") > layoutX.addWidget(self.XLineEdit) > layout5.addLayout(layoutX) > > layoutY = QHBoxLayout(None,0,6,"layoutY") > > self.YLabel = QLabel(self,"YLabel") > layoutY.addWidget(self.YLabel) > > self.YLineEdit = QLineEdit(self,"YLineEdit") > layoutY.addWidget(self.YLineEdit) > layout5.addLayout(layoutY) > > layoutZ = QHBoxLayout(None,0,6,"layoutZ") > > self.ZLabel = QLabel(self,"ZLabel") > layoutZ.addWidget(self.ZLabel) > > self.ZLineEdit = QLineEdit(self,"ZLineEdit") > layoutZ.addWidget(self.ZLineEdit) > layout5.addLayout(layoutZ) > layout9.addLayout(layout5) > layout10.addLayout(layout9) > > self.ButtonGroup = QButtonGroup(self,"ButtonGroup") > > self.CircleRadioButton = > QRadioButton(self.ButtonGroup,"CircleRadioButton") > self.CircleRadioButton.setGeometry(QRect(20,50,56,21)) > > self.SquareRadioButton = > QRadioButton(self.ButtonGroup,"SquareRadioButton") > self.SquareRadioButton.setGeometry(QRect(20,20,64,21)) > self.SquareRadioButton.setChecked(1) > layout10.addWidget(self.ButtonGroup) > layout14.addLayout(layout10) > > layout11 = QHBoxLayout(None,0,6,"layout11") > > self.NewClipButton = QPushButton(self,"NewClipButton") > layout11.addWidget(self.NewClipButton) > > self.DeleteClipButton = QPushButton(self,"DeleteClipButton") > layout11.addWidget(self.DeleteClipButton) > > self.CloseButton = QPushButton(self,"CloseButton") > layout11.addWidget(self.CloseButton) > layout14.addLayout(layout11) > > DialogLayout.addLayout(layout14,0,0) > > self.languageChange() > > self.resize(QSize(340,427).expandedTo(self.minimumSizeHint())) > self.clearWState(Qt.WState_Polished) > > > self.connect(self.NewClipButton,SIGNAL("clicked()"),self.NewClipButton_clicked) > > self.connect(self.DeleteClipButton,SIGNAL("clicked()"),self.DeleteClipButton_clicked) > > self.connect(self.CloseButton,SIGNAL("clicked()"),self.CloseButton_clicked) > > > def languageChange(self): > self.setCaption(self.__tr("RAT")) > self.ClipListView.header().setLabel(0,self.__tr("Column 1")) > self.ClipListView.clear() > item = QListViewItem(self.ClipListView,None) > item.setText(0,self.__tr("New Item")) > > self.WidthLabel.setText(self.__tr("Width/Radius")) > self.OriginLabel.setText(self.__tr("Origin")) > self.XLabel.setText(self.__tr("X")) > self.YLabel.setText(self.__tr("Y")) > self.ZLabel.setText(self.__tr("Z")) > self.ButtonGroup.setTitle(self.__tr("Clip Type")) > self.CircleRadioButton.setText(self.__tr("Circle")) > self.SquareRadioButton.setText(self.__tr("Square")) > self.NewClipButton.setText(self.__tr("New")) > self.DeleteClipButton.setText(self.__tr("Delete")) > self.CloseButton.setText(self.__tr("Close")) > > > def NewClipButton_clicked(self): > print "Dialog.NewClipButton_clicked(): Not implemented yet" > > def DeleteClipButton_clicked(self): > print "Dialog.DeleteClipButton_clicked(): Not implemented yet" > > def CloseButton_clicked(self): > print "Dialog.CloseButton_clicked(): Not implemented yet" > > def __tr(self,s,c = None): > return qApp the __tr() method of Dialog becomes name-mangled in descendents to _Dialog__tr. See http://docs.python.org/tut/node11.html#SECTION0011600000000000000000 James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From jacob.kroon at gmail.com Sat Mar 18 09:57:37 2006 From: jacob.kroon at gmail.com (Jacob Kroon) Date: Sat, 18 Mar 2006 15:57:37 +0100 Subject: Generating exceptions from C In-Reply-To: <441BF396.2090102@gmail.com> References: <441BF396.2090102@gmail.com> Message-ID: <441C1FE1.8030504@gmail.com> I'll just reply to myself what I've found out so far: > 1. PyErr_NewException() creates the exception _class_, not the > instance right ? > Looks like it does yes. It doesn't even seem right to talk about an _instance_ of an exception... > 2. Is PyErr_SetString() the correct way to raise exceptions ? After looking at error.c in the python sources, it looks like that function sets the global exception type and value variables to the provided arguments. > 3. Besides the error message I pass to PyErr_SetString(), I also want > to pass additional return > data together with the exception. But this should be attached to the > exception _instance_, > not the class, am I right ? > The right way seems to be to create a tuple that consists of the string message, and any additional data, and pass the tuple in PyErr_SetObject(). > 4. If I am supposed to attach it to the exception instance, how would > I do that ? I never have a > pointer to the exception instance, just the class. As said previously, there is never an instance of the exception, data is passed in the "value" argument. Does the comments above make sense? --Jacob From sullivanz.pku at gmail.com Tue Mar 28 11:52:49 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 28 Mar 2006 08:52:49 -0800 Subject: How to inplement Session in CGI In-Reply-To: <4428eea8$0$27048$626a54ce@news.free.fr> References: <1143525508.503801.54770@i39g2000cwa.googlegroups.com> <4428eea8$0$27048$626a54ce@news.free.fr> Message-ID: <1143564769.940182.29570@z34g2000cwc.googlegroups.com> bruno at modulix ??? > Sullivan WxPyQtKinter wrote: > > Python disappointly failed to provide a convinient cgi session > > management module. > > Probably because there are much better options for web programming in > Python ? > Really? Then what is it? From duncanm255 at hotmail.com Wed Mar 1 16:34:26 2006 From: duncanm255 at hotmail.com (D) Date: 1 Mar 2006 13:34:26 -0800 Subject: Stopping Windows Service In-Reply-To: <44060E9C.7050607@websafe.com> References: <1141245687.785561.24450@j33g2000cwa.googlegroups.com> <44060E9C.7050607@websafe.com> Message-ID: <1141248866.523051.91950@p10g2000cwp.googlegroups.com> Thanks guys. Larry - I inserted the rc lines right after I do the listen() and the service is not functioning properly (service is terminating). Where am I going wrong here? Doug From exarkun at divmod.com Fri Mar 10 16:23:21 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 10 Mar 2006 16:23:21 -0500 Subject: epydoc help (putting XML in docstrings) In-Reply-To: <1142023769.899027.114920@j33g2000cwa.googlegroups.com> Message-ID: <20060310212321.6122.1470348894.divmod.quotient.14686@ohm> On 10 Mar 2006 12:49:29 -0800, "programmer.py at gmail.com" wrote: >Hi everyone! I'm documenting some functions that return XML strings. >I'd like to have `sample' xml show up in my epydoc generated >documentation. However, epydoc does not like the indentation of the >XML and gives me this error -> > >L28: Error: Improper paragraph indentation. > >Here is a simple function that epydoc does not like: > >def test(): > """ > Return an XML string that looks like this:: > > > 123 > D > ... > > > @return: XML string. > """ > pass > >[jwyant at L-JWYANT:daplib]$ epydoc test.py >Importing 1 modules. > [.] >Building API documentation for 1 modules. > [.] >=========================================================================== >C:\cygwin\home\jwyant\code\dap-support\python\daplib\test.py >In test.test docstring (line 2): >--------------------------------------------------------------------------- > L5: Error: Improper paragraph indentation. > >Any ideas? > def test(): """ Return an XML string that looks like this:: 123 D ... @return: XML string. """ exarkun at kunai:~$ epydoc test.py Importing 1 modules. [.] Building API documentation for 1 modules. [.] Writing HTML docs (10 files) to 'html'. [..........] Jean-Paul From eugene_druker at yahoo.com Tue Mar 21 10:27:16 2006 From: eugene_druker at yahoo.com (ezd) Date: 21 Mar 2006 07:27:16 -0800 Subject: TKinter problem In-Reply-To: <1142942584.351478.98680@i39g2000cwa.googlegroups.com> References: <1142942584.351478.98680@i39g2000cwa.googlegroups.com> Message-ID: <1142954836.453371.118900@e56g2000cwe.googlegroups.com> C D Wood wrote: > To whom this may concern, > Below is the source code, which > > demonstrates a > problem I am having making a GUI for my python project work. > 'table.txt' > is a file that is read from the same folder. > > My code writes to a text file 'table.txt', and 'table.txt' is displayed > in > the GUI. The user can generate new data at the click of a button > which re-writes 'table.txt', but I can only add the new table to the > GUI > window rather than 'update' the existing one. > > Any assistance would be much appreciated, > > Regards, > Christian Wood. > Part III Aerospace Engineering > University of Southampton, UK. > > ################################################################## > from Tkinter import * > > #Tkinter User Interface > class MoC: > def __init__(self, master): > frame = Frame(master, width=600, height=800, bd=1) > frame.pack() > > #Button frame > iframe4 = Frame(frame, bd=2, relief=SUNKEN) > #Using this button below, I want to update the text box in iframe5. > Button(iframe4, text='Display table.txt', > command=self.DisplayUpdate).pack(side=LEFT, padx=5) > Button(iframe4, text='Quit', command=self.quit).pack(side=LEFT, > padx=5) > iframe4.pack(expand=1, fill=X, pady=10, padx=5) > > #Text box frame > iframe5 = Frame(frame, bd=2, relief=SUNKEN) > text=Text(iframe5, height=10, width =70) > fd = open('table.txt') #table.txt must be in the same folder > lines = fd.read() > fd.close() > text.insert(END, lines) > text.pack(side=LEFT, fill=X, padx=5) > sb = Scrollbar(iframe5, orient=VERTICAL, command=text.yview) > sb.pack(side=RIGHT, fill=Y) > text.configure(yscrollcommand=sb.set) > iframe5.pack(expand=1, fill=X, pady=10, padx=5) > > #Command definitions > def quit(self): > root.destroy() > > def DisplayUpdate(self): #The command definition used to update the > display. > #Could I insert a line here to remove the existing frame/text > box first? <<<<<===== > iframe5 = Frame(root, bd=2, relief=SUNKEN) > text = Text(iframe5, height=10, width =70) > fd = open('table.txt') > lines = fd.read() > fd.close() > text.insert(END, lines) > text.pack(side=LEFT, fill=X, padx=5) > sb = Scrollbar(iframe5, orient=VERTICAL, command=text.yview) > sb.pack(side=RIGHT, fill=Y) > text.configure(yscrollcommand=sb.set) > iframe5.pack(expand=1, fill=X, pady=10, padx=5) > > root = Tk() > root.option_add('*font', ('arial', 10)) > all = MoC(root) > root.title('2D Method of Characteristics') > root.update > root.mainloop() What you want probably looks like this: from Tkinter import * class MoC: def __init__(self, master): frame = Frame(master, width=600, height=800, bd=1) frame.pack() iframe4 = Frame(frame, bd=2, relief=SUNKEN) Button(iframe4, text='Display table.txt', command=self.DisplayUpdate).pack(side=LEFT, padx=5) Button(iframe4, text='Quit', command=self._quit).pack(side=LEFT, padx=5) iframe4.pack(expand=1, fill=X, pady=10, padx=5) iframe5 = Frame(frame, bd=2, relief=SUNKEN) self.text=Text(iframe5, height=10, width =70) # read the file in the update function; create Text & Scrollbar only once self.text.pack(side=LEFT, fill=X, padx=5) sb = Scrollbar(iframe5, orient=VERTICAL, command=self.text.yview) sb.pack(side=RIGHT, fill=Y) self.text.configure(yscrollcommand=sb.set) iframe5.pack(expand=1, fill=X, pady=10, padx=5) self.DisplayUpdate() def _quit(self): # quit is a keyword in python 2.4 IDE root.destroy() def DisplayUpdate(self): fd = open('table.txt') lines = fd.read() fd.close() self.text.config(state=NORMAL) self.text.delete(1.0, END) self.text.insert(END, lines) self.text.config(state=DISABLED) # previous 4 lines are to make the text READONLY, see more in: # http://www.pythonware.com/library/tkinter/introduction/x8309-patterns.htm root = Tk() root.option_add('*font', ('arial', 10)) all = MoC(root) root.title('2D Method of Characteristics') root.update root.mainloop() ezd From vincenzo.cacciatore at gmail.com Wed Mar 15 10:06:16 2006 From: vincenzo.cacciatore at gmail.com (LabWINC) Date: 15 Mar 2006 07:06:16 -0800 Subject: FIR filtering In-Reply-To: References: <1142428703.224948.317700@u72g2000cwu.googlegroups.com> Message-ID: <1142435176.837718.42220@v46g2000cwv.googlegroups.com> What's gnuradio? From eight02645999 at yahoo.com Fri Mar 17 20:32:16 2006 From: eight02645999 at yahoo.com (eight02645999 at yahoo.com) Date: 17 Mar 2006 17:32:16 -0800 Subject: insert chars into string Message-ID: <1142645536.492888.216530@g10g2000cwb.googlegroups.com> hi is there a string method to insert characters into a string? eg str = "abcdef" i want to insert "#" into str so that it appears "abc#def" currently what i did is convert it to a list, insert the character using insert() and then join them back as string.. thanks From justin.frost at gmail.com Fri Mar 10 20:01:07 2006 From: justin.frost at gmail.com (MakaMaka) Date: 10 Mar 2006 17:01:07 -0800 Subject: creating variable in root namespace from module In-Reply-To: References: <1141976796.594066.229210@e56g2000cwe.googlegroups.com> <1142009812.786850.218860@z34g2000cwc.googlegroups.com> <1142013955.214142.124160@e56g2000cwe.googlegroups.com> <1142014772.594826.240480@z34g2000cwc.googlegroups.com> Message-ID: <1142038867.673269.248800@i39g2000cwa.googlegroups.com> Ok, but it seems to be working exactly as I need it to right now under win32. I'll try it on linux. Can you suggest an alternative method? Or suggest when this won't work? Thanks, -Justin From tim.hochberg at ieee.org Tue Mar 7 19:45:09 2006 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Tue, 07 Mar 2006 17:45:09 -0700 Subject: Cryptographically random numbers In-Reply-To: <7xek1drgvi.fsf@ruckus.brouhaha.com> References: <1141515788.580039.98240@v46g2000cwv.googlegroups.com> <7xveuqvube.fsf@ruckus.brouhaha.com> <1141768329.809872.273310@j52g2000cwj.googlegroups.com> <7xek1drgvi.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Tuvas" writes: > >>I've actually done the tests on this one, it's actually faster to use >>the += than a list, odd as it may sound. > > > Frederik explained the reason; there's an optimization in Python 2.4 > that I'd forgotten about, for that specific case. It's not in earlier > versions. It's a bit fragile in 2.4: > > a = '' > for x in something: > a += g(x) > > is fast, but if a is aliased, Python can't do the optimization, so > > a = '' > b = a > for x in something: > a += g(x) > > is slow. Is this really true? After the first time through the loop, 'a' won't be aliased any more since strings are immutable. After that the loops should be equivalent. I tried this out to see if I could see a timing difference, in case I was missing something, with Python 2.4.1, the following two snippets timed essentially the same for N up to 2**20 (I didn't try any higher): def concat1(): a = '' for x in ' '*N: a += x return a def concat2(): a = '' b = a for x in ' '*N: a += x return a Regards, -tim > Figuring out which case to use relies on CPython's reference > counting storage allocator (the interpreter keeps track of how many > pointers there are to any given object) and so the optimization may > not be feasible at all in other implementations which use different > storage allocation strategies (e.g. Lisp-style garbage collection). > > All in all I think it's best to use a completely different approach > (something like StringBuffer) but my effort to start a movement here > on clpy a couple months ago didn't get anywhere. From siasookhteh at gmail.com Mon Mar 27 14:56:14 2006 From: siasookhteh at gmail.com (Siah) Date: 27 Mar 2006 11:56:14 -0800 Subject: What is Caching my DB In-Reply-To: <1143486383.353778.142250@e56g2000cwe.googlegroups.com> References: <1143486383.353778.142250@e56g2000cwe.googlegroups.com> Message-ID: <1143489374.322846.67580@t31g2000cwb.googlegroups.com> Sorry, this post had to go on Django Users group. I'll post it there. You may ignore this post here. Sia From nitrogenycs at web.de Thu Mar 9 14:18:13 2006 From: nitrogenycs at web.de (Matthias) Date: Thu, 09 Mar 2006 20:18:13 +0100 Subject: PyRun_String References: Message-ID: Am Thu, 09 Mar 2006 20:06:54 +0100 hat Duncan Booth geschrieben: > Matthias wrote: > >> Log("Marker 1"); >> Py_XDECREF( PyRun_String( "print 'Hi!'", Py_single_input, Dict, Dict) ); >> Log("Marker 2"); >> >> The output looks like >> >> Marker 1 >> Hi! >> Hi! >> Marker 2 >> >> Obviously Hi! is printed twice. > > Py_XDECREF is a C macro. If you check its definition you will see that it > does indeed evaluate the argument twice. This is a not uncommon problem > when using macros in C: if in doubt, do not call a macro with anything > as a parameter which has side effects. > > #define Py_XDECREF(op) if ((op) == NULL) ; else Py_DECREF(op) Arrrghh, I've seen the evil side today; C macros are surely devil-sent. I spent hours tracking down this bug, I didn't even consider the Py_XDECREF and concentrated on PyRun_String. It's a pity C doesn't support inline functions. Thanks a lot for pointing this out before I lost my head, Duncan! Maybe Py_XDECREF(op) could be replaced with #define Py_XDECREF(op) {PyObject* obj = (op); if (obj == NULL) ; else Py_DECREF(obj)} but I guess this eats one or two clock cycles too much for other people who use Py_XDECREF. Thanks again! -Matthias From bencvt at gmail.com Tue Mar 21 20:30:47 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 21 Mar 2006 17:30:47 -0800 Subject: Using Dictionaries in Sets - dict objects are unhashable? In-Reply-To: References: Message-ID: <1142991047.118172.313150@v46g2000cwv.googlegroups.com> Gregory Pi?ero wrote: > Hey guys, > > I don't understand why this isn't working for me. I'd like to be able > to do this. Is there another short alternative to get this > intersection? > > [Dbg]>>> set([{'a':1},{'b':2}]).intersection([{'a':1}]) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: dict objects are unhashable Assuming you're using Python 2.4+: >>> d1 = {'a':1, 'b':2, 'c':3, 'd':5} >>> d2 = {'a':1, 'c':7, 'e':6} >>> dict((k, v) for k, v in d1.iteritems() if k in d2) {'a': 1, 'c': 3} Or if you're comparing key/value pairs instead of just keys: >>> dict((k, v) for k, v in d1.iteritems() if k in d2 and d2[k]==v) {'a': 1} Finally, if you're on Python 2.3, use these versions (less efficient but still functional): >>> dict([(k, v) for k, v in d1.iteritems() if k in d2]) {'a': 1, 'c': 3} >>> dict([(k, v) for k, v in d1.iteritems() if k in d2 and d2[k]==v]) {'a': 1} --Ben From Serge.Orlov at gmail.com Sun Mar 19 22:33:20 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 19 Mar 2006 19:33:20 -0800 Subject: whats your favourite object relational mapper? References: <1142819539.741782.189420@v46g2000cwv.googlegroups.com> Message-ID: <1142825600.276731.264950@j33g2000cwa.googlegroups.com> Jean-Paul Calderone wrote: > On 19 Mar 2006 17:52:19 -0800, Serge Orlov wrote: > >Flavio wrote: > >> With so many object relational mappers out there, I wonder which one is > >> the preferred tool among the Pythonists... is there a favourite? > >> > >> Sqlobject, PyDO, SQLAlchemy, dejavu, etc... > > > >Google results: > >Sqlobject ORM: about 17,100 > >PyDO ORM: 469 > >SQLAlchemy ORM: 571 > >dejavu ORM: 659 > > > > axiom orm: about 21,500 > > Although "axiom" is not exactly unique. How about: > > divmod axiom: 34,500 > > Huh. +axiom +python +ORM: 724 +dejavu +python +ORM: 529 From funkyj at gmail.com Fri Mar 17 21:12:57 2006 From: funkyj at gmail.com (funkyj) Date: 17 Mar 2006 18:12:57 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1142589945.078364.32870@i39g2000cwa.googlegroups.com> <1142599685.186209.177630@j33g2000cwa.googlegroups.com> Message-ID: <1142647977.696295.124650@i40g2000cwc.googlegroups.com> wkehowski at cox.net wrote: > It would seem that your program is just filtering the full cartesian > product, right? The solution I'm looking for generates the elements > one-by-one so that it could be used in a loop. One advantage of a generator over filtering the full product is that I, as the user of the generator, am not obligated to iterate over the entire solution space. Are there other _practical_ advantages of generators over mapping & filtering complete sets? From ziga.seilnacht at gmail.com Sat Mar 25 16:58:17 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 25 Mar 2006 13:58:17 -0800 Subject: Why are so many built-in types inheritable? References: <441c6498$1_1@news.cybercity.ch><4424c104_2@newspeer2.tds.net> Message-ID: <1143323897.342734.63080@u72g2000cwu.googlegroups.com> Fabiano Sidler wrote: [snipped] > The problem with this is that the func_code attribute would contain > the code of PrintingFunction instead of func. What I wanted to do, is > to keep the original behaviour, i.e. set the variable __metaclass__ to > DebugMeta and so get debug output, without changing a function and > getting the original function's code object by the func_code > attribute, not PrintigFunction's one. That's why I *must* inherit from > . No, you don't have to: >>> import new >>> import types >>> class DebugFunction(object): ... def __init__(self, func): ... object.__setattr__(self, 'func', func) ... def __get__(self, obj, objtype): ... return new.instancemethod(self, obj, objtype) ... def __call__(self, *args, **namedargs): ... print args, namedargs ... func = object.__getattribute__(self, 'func') ... return func(*args, **namedargs) ... def __getattribute__(self, name): ... func = object.__getattribute__(self, 'func') ... return getattr(func, name) ... def __setattr__(self, name, value): ... func = object.__getattribute__(self, 'func') ... setattr(func, name, value) ... def __delattr__(self, name): ... func = object.__getattribute__(self, 'func') ... delattr(func, name) ... >>> class DebugMeta(type): ... def __new__(meta, name, bases, dict): ... for name, obj in dict.iteritems(): ... if isinstance(obj, types.FunctionType): ... dict[name] = DebugFunction(obj) ... return type.__new__(meta, name, bases, dict) ... >>> class Example(object): ... __metaclass__ = DebugMeta ... def spam(self, *args, **namedargs): ... """Spam spam spam spam. Lovely spam! Wonderful spam!""" ... pass ... >>> e = Example() >>> e.spam('eggs', anwser=42) (<__main__.spam object at ...>, 'eggs') {'anwser': 42} >>> e.spam.__doc__ 'Spam spam spam spam. Lovely spam! Wonderful spam!' >>> e.spam.im_func.func_code ", line 3> > Greetings, > F. Sidler Ziga From bencvt at gmail.com Fri Mar 10 01:49:34 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 9 Mar 2006 22:49:34 -0800 Subject: How to pop random item from a list? References: <1141970390.167455.152820@j52g2000cwj.googlegroups.com> Message-ID: <1141973373.974320.273600@i40g2000cwc.googlegroups.com> flamesrock wrote: > whats the best way to pop a random item from a list?? import random def popchoice(seq): # raises IndexError if seq is empty return seq.pop(random.randrange(len(seq))) --Ben From msoulier at gmail.com Wed Mar 15 09:48:59 2006 From: msoulier at gmail.com (msoulier) Date: 15 Mar 2006 06:48:59 -0800 Subject: Tried Ruby (or, "what Python *really* needs" or "perldoc!") In-Reply-To: <1142397587.151040.35450@j33g2000cwa.googlegroups.com> References: <1142355126.757569.42160@i40g2000cwc.googlegroups.com> <1142397587.151040.35450@j33g2000cwa.googlegroups.com> Message-ID: <1142434139.499666.281590@v46g2000cwv.googlegroups.com> > I have found the Python sidebar VERY helpful: Personally, I can't use local docs on my desktop as they may not be the same version of the docs for the Python distro running on the server that I'm deploying on. I usually go to python.org and use the wayback machine to look at the old docs for the release that I'm on. But, if Python would match Perl for docs available on the command-line, then I'd have it all at my fingertips. I simply don't understand why this is not being done. When I'm coding in C, I use the manpages on the remote host so that I know the docs are correct for my target. Why can't I do that in Python? It's yet another thing that my Perl-using coworkers point out as a Python weakness. Mike From n.estner at gmx.de Sun Mar 26 19:36:20 2006 From: n.estner at gmx.de (nikie) Date: 26 Mar 2006 16:36:20 -0800 Subject: PIL & image size reduction script References: Message-ID: <1143419780.383974.88180@t31g2000cwb.googlegroups.com> Philippe Martin wrote: > Hi, > > Thanks to the NG, I got the script hereunder working. > > 1) I am not certain that the call to convert does much (checking the doc) I think you only need it if your source image comes in a format that can't be stored into a jpeg file (e.g. 8-bit paletted). You'll need that if you're converting from GIF files, for example. It shouldn't hurt otherwise. > 2) Can this be improved as far as the final image size in (X,Y) ? I'm not sure if I get you: You tell the image object it's new (X,Y)-size in the resize method, don't you? > For instance, passing a large .jpg with a target byte size of 7000, I get > final (X,Y) results around (213, 174) ... but might want to strech it a bit > while keeping the byte size. If I got you right, you want to compress the image to a certain file size. Maybe you should try optimizing the additional save parameters for the jpeg encoder. (http://www.pythonware.com/library/pil/handbook/formats.htm). Try reducing the "quality" parameter. l_image.save(l_tmp_file_name, quality=25) Hope this helps. Niki From flashkNO at SPAMgmail.com Sat Mar 4 19:19:47 2006 From: flashkNO at SPAMgmail.com (Farshid Lashkari) Date: Sat, 04 Mar 2006 16:19:47 -0800 Subject: Passing a method indirectly In-Reply-To: <1141516407.480315.22400@e56g2000cwe.googlegroups.com> References: <1141516407.480315.22400@e56g2000cwe.googlegroups.com> Message-ID: <88qOf.1174$fL3.1030@fed1read01> You don't need to pass the object along with the method. The method is bound to the object. Simply call the method by itself: def ObjApply(method): method() class Test: def test1 (self): print "Hello" def test2 (self): ObjApply(self.test1) ta = Test () ta.test2 () If you wanted to pass an unbound method, then it would look like the following: def ObjApply(object,method): method(object) class Test: def test1 (self): print "Hello" def test2 (self): ObjApply(self,Test.test1) ta = Test () ta.test2 () From gshepherd281281 at yahoo.com Sat Mar 25 19:18:13 2006 From: gshepherd281281 at yahoo.com (ProvoWallis) Date: 25 Mar 2006 16:18:13 -0800 Subject: noobie mkdir problem/question In-Reply-To: <1143330785.575857.201110@u72g2000cwu.googlegroups.com> References: <1143322904.618585.188740@t31g2000cwb.googlegroups.com> <1143330785.575857.201110@u72g2000cwu.googlegroups.com> Message-ID: <1143332293.822910.17680@v46g2000cwv.googlegroups.com> I understand that but I'm still puzzled. Is this the reason why I can't write files to this directory? The xrefs directory is created the way I expect it would be using mkdir but I can't seem to write to it. I thought that my results would be written to the xrefs directory here but they're ending up in the original folder not the subfolder. outputFile = open(os.path.join(xrefs,outputFname), 'w') outputFile.write(data) outputFile.close() What am I missing? jordan.taylor2 at gmail.com wrote: > if (os.path.isdir(xrefs) == 0): > os.mkdir(xrefs) > > -------------------------------------------- > > os.path.isdir(stuff) returns > True or False From bj_666 at gmx.net Mon Mar 20 16:33:52 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 20 Mar 2006 22:33:52 +0100 Subject: A Frame-space syntax ? - Re: global, globals(), _global ? References: <1hc8e79.imz7zd16x7t3sN%aleaxit@yahoo.com> <1hc97un.15qyd7bycer0fN%aleaxit@yahoo.com> <1hca6up.az5e3hn3t4iqN%aleaxit@yahoo.com> Message-ID: In , robert wrote: > Marc 'BlackJack' Rintsch wrote: >> In , robert wrote: >> >>>The fact is: >>>* Python has that big problem with unnecessary barriers for nested frame >>>access - especially painfull with callback functions where you want to >>>put back data into the calling frame. >> >> >> You mean accessing the locals in the function that invoked the callback!? >> That sounds ugly. Makes it hard to decouple the caller and the callee >> here. >> > > That is a frequent need. For read's its anyway wired up. E.g. callbacks: > > def f(): > a=1 > def g(var): > print a # automatic > .lastvar=var # binds in outer frame > run_w_callback(1,2,g) > print lastvar > > > Ruby blocks for example do that regularly. I think you're trying to write Ruby programs in Python here. Just define a callable object as callback:: class G: def __init__(self, a): self.a = a self.lastvar = None def __call__(self, var): print self.a self.lastvar = var def f2(): g = G(1) run_w_callback(1, 2, g) print g.lastvar Ciao, Marc 'BlackJack' Rintsch From pydecker at gmail.com Wed Mar 8 08:55:10 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 8 Mar 2006 08:55:10 -0500 Subject: RAD tutorials and tools for GUI development with Python? In-Reply-To: <16de708d0603080251t3f62958btea3e13535bc4312c@mail.gmail.com> References: <16de708d0603080251t3f62958btea3e13535bc4312c@mail.gmail.com> Message-ID: On 3/8/06, Arthur Pemberton wrote: > Hey guys, > > I would really like to code a few more widely useable apps, but coding the > GUI just seems so boring and unnecessarily complex. Maybe I was spoilt by > Borland's Delphi/Kylix. But is there any way to do as little coding of the > GUI as possible, and worry about the logic? The best I've seen is using one > tool with a modification to output python code, which then has to be > regenerated after any change to the GUI, which to me, kinda defeats the > "rapid" in RAD. > > Thanks, advice would be much apperciated. If it helps to know, I am > currently more interested in Python/Gtk (but not because I particularly like > the look of Gtk) I would recommend that you take a look at Dabo (http://dabodev.com). They are in the process of developing exactly the sort of GUI design tools you are looking for. They're not 100% of the way there yet, as the project is basically two guys who do this in their free time (and apparently never sleep!). On the Documentation page of their site is a list of screencasts where you can see the GUI design tools in action. -- # p.d. From msuemnig at jjhill.org Wed Mar 29 17:41:23 2006 From: msuemnig at jjhill.org (msuemnig at jjhill.org) Date: 29 Mar 2006 14:41:23 -0800 Subject: Apache and Python and Ubuntu Message-ID: <1143672083.347654.81330@v46g2000cwv.googlegroups.com> I've create an Ubuntu Linux box, which comes pre-installed with Python (I've added the libapache2-mod-python throught the app manager). I've created .cgi and .py simple programs in the www root of apache. The problem is the programs just dump the contents to the browser in plain text. Or, in the case of the .py files, I am prompted to download the .py file. How can I get apache to recognize that it should execute the .cgi script? Is there any special thing I need to do to apache to get it to know that the python interpreter should be used for all .cgi files? Thanx all for your help in advance! pen From orsenthil at gmail.com Mon Mar 6 23:55:13 2006 From: orsenthil at gmail.com (Phoe6) Date: 6 Mar 2006 20:55:13 -0800 Subject: New python.org website Message-ID: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> beta.python.org evolved very nice and noticed today the new python.org website going live. There is a change in the look n feel, wherein it looks "more official" and maximum possible information about python is now directly accessible from the home page itself. Kudoes to the design team. Senthil http://phoe6.livejournal.com From larry.bates at websafe.com Wed Mar 1 16:01:48 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 01 Mar 2006 15:01:48 -0600 Subject: Proper class initialization In-Reply-To: References: Message-ID: Christoph Zwerschke wrote: > Usually, you initialize class variables like that: > > class A: > sum = 45 > > But what is the proper way to initialize class variables if they are the > result of some computation or processing as in the following silly > example (representative for more: > > class A: > sum = 0 > for i in range(10): > sum += i > > The problem is that this makes any auxiliary variables (like "i" in this > silly example) also class variables, which is not desired. > > Of course, I could call a function external to the class > > def calc_sum(n): > ... > > class A: > sum = calc_sum(10) > > But I wonder whether it is possible to put all this init code into one > class initialization method, something like that: > > class A: > > @classmethod > def init_class(self): > sum = 0 > for i in range(10): > sum += i > self.sum = sum > > init_class() > > However, this does not work, I get > TypeError: 'classmethod' object is not callable > > Is there another way to put an initialization method for the class A > somewhere *inside* the class A? > > -- Christoph Although I've never had the need for something like this, this works: class A: sum=0 for i in range(10): sum+=i del i or moving the initialization into __init__ method isn't terribly inefficient unless are are creating LOTS of instances of the same class. class A: def __init__(self): self.sum=0 for i in range(10): self.sum+=i or you can do the do it before you instantiate the class class A: def __init__(self, initialvalue=None): if initialvalue is not None: self.sum=initialvalue else: self.sum=0 for i in range(10): sum+=i b=A(sum) c=A(sum) -Larry Bates From davecook at nowhere.net Thu Mar 16 20:56:36 2006 From: davecook at nowhere.net (Dave Cook) Date: Fri, 17 Mar 2006 01:56:36 GMT Subject: Python / glade fundamentals References: Message-ID: On 2006-03-16, Doug wrote: > Can someone tell me why I do not get a connection between the events and > the functions in the sample below. GUI window appears OK, just no > connections seem to be made. > I am new to this so may be missing something fundamental. This might be relevant: http://www.async.com.br/faq/pygtk/index.py?req=show&file=faq03.003.htp Dave Cook From reply.in.the.newsgroup at my.address.is.invalid Tue Mar 21 05:47:15 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 21 Mar 2006 11:47:15 +0100 Subject: TaskQueue References: <1142937223.607170.7160@v46g2000cwv.googlegroups.com> Message-ID: Raymond Hettinger: >There are some competing approaches. One is to attach sentinel objects >to the end of the line as a way for consumer threads to know that they >should shut down. Then a regular t.join() can be used to block until >the consumers threads have shut-down. This approach is >straight-forward, but it depends on 1) complicating the consumer logic >to include sentinel detection and thread shut-down, Writing this observation was way more complicated than writing the code that's required to implement it :-) if task is None: break I use 'None' as the sentinel. This is a larger snippet from my own threadpool with the context of this code: def run(self): while True: task = self.workQueue.get() if task is None: break try: task.do() except: task.unhandledException() self.resultQueue.put(task) >2) complicating the producer logic to append one sentinel for each consumer >when the data stream is done for i in range(self.numberOfThreads): self.workQueue.put(None) Again, more characters in your observation than in the code. >3) actually knowing when the data stream is done. def doingWork(self): return self.numberOfTasks > 0 Which is possible because of: def putTask(self,task): self.workQueue.put(task) self.numberOfTasks += 1 def getTask(self): task = self.resultQueue.get() self.numberOfTasks -= 1 return task -- Ren? Pijlman Wat wil jij leren? http://www.leren.nl From newptcai at gmail.com Wed Mar 29 10:48:58 2006 From: newptcai at gmail.com (Peter Cai) Date: Wed, 29 Mar 2006 23:48:58 +0800 Subject: pythonw doesn't work! Message-ID: I can't open IDEL or any .pyw file. When I click on IDEL.pyw, nothing happens! But python itself is ok. Has anybody met this problem? -------------- next part -------------- An HTML attachment was scrubbed... URL: From ram0812 at hotmail.com Wed Mar 15 14:16:01 2006 From: ram0812 at hotmail.com (Raja Raman Sundararajan) Date: 15 Mar 2006 11:16:01 -0800 Subject: pyRTF and cells Message-ID: <1142450161.536293.256580@i40g2000cwc.googlegroups.com> Hello, I have been playing around with pyRTF module for generating rtf documents. Its a very nice tool that fits my basic needs. However I have a problem controlling cells in a table. I am not able to 1. do an align right of contents inside a cell 2. set backgroundcolor of a cell 3. I wonder if there is a property to set cell height (?) Do you guys have any input on this? /R From sullivanz.pku at gmail.com Sat Mar 11 05:29:13 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 11 Mar 2006 02:29:13 -0800 Subject: Can not find a file in CMD model python when everything is OK in IDLE In-Reply-To: References: <1142072226.386475.313160@p10g2000cwp.googlegroups.com> Message-ID: <1142072953.820921.35510@p10g2000cwp.googlegroups.com> Sorry, I mistyped the line. In the program it IS: f=open("ticket.txt"), no '\' included. From jeremy at emperorlinux.com Fri Mar 3 17:20:24 2006 From: jeremy at emperorlinux.com (Jeremy Moles) Date: Fri, 03 Mar 2006 17:20:24 -0500 Subject: [ANNOUNCE] PyIW and PyWPA Message-ID: <1141424424.2509.15.camel@localhost.localdomain> Sorry for the double-post; that's what I get for using busted, Dapper Evolution. :) ---------------------------------------------------------------- Many updates to the modules I'm writing for interacting with wireless networking in Linux using Python. PyIW - Python bindings to libiw. PyWPA - Python bindings/wrapper for wpa_supplicant. They can be found here: http://downloads.emperorlinux.com/contrib/pyiw http://downloads.emperorlinux.com/contrib/pywpa From steven.bethard at gmail.com Wed Mar 1 18:13:17 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 01 Mar 2006 16:13:17 -0700 Subject: PythonWin: any way to delete all objects without exiting and without doing it with "del"? In-Reply-To: <1141250922.615071.68700@i39g2000cwa.googlegroups.com> References: <1141250922.615071.68700@i39g2000cwa.googlegroups.com> Message-ID: dananrg at yahoo.com wrote: > In PythonWin, is there any way to bulk-delete all objects without using > "del object" for each, and without having to exit out of PythonWin? I think you just want to modify the globals() dict: >>> list(globals()) ['__builtins__', 'text', 'glob', 'pywin', 're', 'match', 'basename', '__name__', 'line', 'foo', 'os', '__doc__', 'fn'] >>> for name in list(globals()): ... if name != 'pywin' and name[:2] != '__': ... del globals()[name] ... >>> del name >>> list(globals()) ['__builtins__', 'pywin', '__name__', '__doc__'] Be careful though, I think there's a few things in there you might not want to ``del`` (e.g. ``pywin``). STeVe From jes at nl.demon.net Sun Mar 12 10:00:02 2006 From: jes at nl.demon.net (Jim Segrave) Date: Sun, 12 Mar 2006 15:00:02 -0000 Subject: time series calculation in list comprehension? References: <1142012049.892323.103060@v46g2000cwv.googlegroups.com> Message-ID: <1218drig7l9fkad@corp.supernews.com> In article <1142012049.892323.103060 at v46g2000cwv.googlegroups.com>, falcon wrote: >Is there a way I can do time series calculation, such as a moving >average in list comprehension syntax? I'm new to python but it looks >like list comprehension's 'head' can only work at a value at a time. I >also tried using the reduce function and passed in my list and another >function which calculates a moving average outside the list comp. ... >but I'm not clear how to do it. Any ideas? Thanks. I used the following to return an array of the average of the last n values -it's not particularly pretty, but it works # set number of values to average weighting = 10 # an array of values we want to calculate a running average on ratings = [] # an array of running averages running_avg = [] # some routine to fill ratings with the values r = random.Random() for i in range(0, 20): ratings.append(float(r.randint(0, 99))) for i in range(1, 1 + len(ratings)): if i < weighting: running_avg.append(ratings[i - 1]) else: running_avg.append(reduce(lambda s, a: s+ a, ratings[i - weighting : i]) / len(ratings[i - weighting : i])) for i in range(0, len(ratings)): print "%3d: %3d %5.2f" % (i, ratings[i], running_avg[i]) sample output: 0: 34 34.00 1: 28 28.00 2: 58 58.00 3: 16 34.00 4: 74 44.00 5: 32 45.00 6: 74 49.00 7: 21 50.25 8: 78 51.25 9: 28 50.25 10: 32 39.75 11: 93 57.75 12: 2 38.75 13: 7 33.50 14: 8 27.50 15: 30 11.75 16: 1 11.50 17: 8 11.75 18: 40 19.75 19: 8 14.25 For all but the first 3 rows, the third column is the average of the values in the 2nd column for this and the preceding 3 rows. -- Jim Segrave (jes at jes-2.demon.nl) From http Mon Mar 13 05:55:02 2006 From: http (Paul Rubin) Date: 13 Mar 2006 02:55:02 -0800 Subject: SSL/TLS - am I doing it right? References: <1142240607.501914.4390@j52g2000cwj.googlegroups.com> <1142247180.180132.256110@v46g2000cwv.googlegroups.com> Message-ID: <7xlkvehawp.fsf@ruckus.brouhaha.com> "Frank Millman" writes: > I was hoping to avoid this step. The point of the exercise for me is > encryption. I am not too worried about authentication. The next step in > my app is for the client to enter a user id and password, and the > server will not proceed without verifying this. That is a total disaster without authentication, since it means the client can reveal the password to an imposter. From pitmairen at gmail.com Mon Mar 6 13:08:44 2006 From: pitmairen at gmail.com (Pitmairen) Date: 6 Mar 2006 10:08:44 -0800 Subject: Fetch info from website and write to txt file. Message-ID: <1141668524.914676.252460@z34g2000cwc.googlegroups.com> I want to make a program that get info from a website and prints it out in a txt file. I made this: import urllib f = urllib.urlopen("http://www.imdb.com/title/tt0407304/") s = f.read() k = open("test.txt","w") k.write(s) k.close() f.close() That saves all the html code into the test.txt file. But if i for example only want the genre, plot outline and Cast overview to be written to the txt file. How can i do that? And another problem i have: If the txt file i want the information to be saved in already have some text saved in it. How can i save the info from the website between the text that was there before? for example: blablablablablablablabla blablablablablablablabla blablablablablablablabla (inset info from website here) blablablablablablablabla blablablablablablablabla blablablablablablablabla Pitmairen From peter at engcorp.com Mon Mar 27 09:01:08 2006 From: peter at engcorp.com (Peter Hansen) Date: Mon, 27 Mar 2006 09:01:08 -0500 Subject: "For" loop and list comprehension similarity In-Reply-To: <1143464640.463220.283090@i40g2000cwc.googlegroups.com> References: <1143396590.320442.94920@t31g2000cwb.googlegroups.com> <1143414870.330921.305890@j33g2000cwa.googlegroups.com> <1143464640.463220.283090@i40g2000cwc.googlegroups.com> Message-ID: s.lipnevich at gmail.com wrote: > Do you think this discussion is a proof that the following principle > got violated, or do you think that "loop with condition" is not such an > atomic thing to be subject to this: "There should be one -- and > preferably only one -- obvious way to do it." Mitja's suggestion was the one obvious way. The others are all interesting, maybe even preferable in some cases, but I don't think most experienced Python programmers would be more likely to start with one of them than with the simple for-loop-with-explicit-test. -Peter From fulvio at pc.jaring.my Wed Mar 22 06:08:59 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Wed, 22 Mar 2006 19:08:59 +0800 Subject: Some info In-Reply-To: <4420909E.3080208@v.loewis.de> References: <1142610889.512781.69650@j33g2000cwa.googlegroups.com> <1142977513.263383.88410@i39g2000cwa.googlegroups.com> <4420909E.3080208@v.loewis.de> Message-ID: <200603221908.59838.fulvio@pc.jaring.my> Hello, I'm very new of Python programming. I just wrote some hundred lines of a programm. Now, I'd like to go some step farther and make a disk cataloger. There are plenty for win, but few for linux. So, I'd like to write one which is for win and linux. I'm, actually, a bit stuck on how to collect informations regarding disk names (CDroms or USB HDs). The matter is rather difficult if is suppose to make the programm running for linux as much as it would do for MSW. Suggestions are very welcome. Fulvio From mhellwig at xs4all.nl Wed Mar 22 19:46:39 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Thu, 23 Mar 2006 01:46:39 +0100 Subject: don't understand popen2 Message-ID: <4421effd$0$11070$e4fe514c@news.xs4all.nl> Hi all, I was doing some popen2 tests so that I'm more comfortable using it. I wrote a little python script to help me test that (testia.py): --------------------------------- someline = raw_input("something:") if someline == 'test': print("yup") else: print("nope") --------------------------------- And another little thing that does it's popen2 stuff: --------------------------------- import popen2 std_out, std_in = popen2.popen2("testia.py") x=std_out.readline() print(x) std_in.writelines("notgood") x=std_out.readline() print(x) --------------------------------- Now what I expected was that I got the return one the first line: "something:" and on the second "nope", but instead of that I got: >>> something: Traceback (most recent call last): File "F:\coding\pwSync\popen_test\popen_test.py", line 8, in ? std_in.writelines("notgood") IOError: [Errno 22] Invalid argument >>> I played around a bit with flush, write and the order of first writing and then reading, the best I can get is no error but still not the expected output. I googled a bit copied some examples that also worked on my machine, reread the manual and the only conclusion I have is that I don't even understand what I'm doing wrong. Would you please be so kind to explain my wrong doing? (python 2.4 + win32 extensions on XPProSP2) Thanks in advance! -- mph From roy at panix.com Wed Mar 8 07:49:35 2006 From: roy at panix.com (Roy Smith) Date: Wed, 08 Mar 2006 07:49:35 -0500 Subject: New python.org website References: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> <1141737431.437281.178860@z34g2000cwc.googlegroups.com> <1141757397.508448.296600@e56g2000cwe.googlegroups.com> <440ea6c0$0$38658$edfadb0f@dread12.news.tele.dk> Message-ID: The first two links on the "News and Announcements" are dead -- they get you a "404 File Not Found". I've opened a critical ticket on this in the bug tracker. I see there's another ticket open already on a similar issue. My recommendation would be that if these can't be resolved in very short order. to revert to the old site until these are fixed. From johnjsal at NOSPAMgmail.com Thu Mar 30 10:48:19 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 30 Mar 2006 15:48:19 GMT Subject: RELEASED Python 2.4.3, final. In-Reply-To: References: Message-ID: <75TWf.1863$No6.41851@news.tufts.edu> Fredrik Lundh wrote: > John Salerno wrote: > >>> Assuming no major bugs pop up, the next release of Python will >>> be Python 2.5 (alpha 1), with a final 2.4.4 release of Python >>> shortly after the final version of Python 2.5. >> Why would 2.4.4 come out after the final release of 2.5? > > the 2.X.Y releases are bugfix releases, which mainly contain things discovered > and fixed during development of 2.(X+1). releasing the last 2.X.Y maintenance > release *after* releasing 2.(X+1) final is a good way to make sure that nothing > got left out. > > > > > Thanks guys! From kp8 at mac.com Wed Mar 15 19:45:10 2006 From: kp8 at mac.com (kpp9c) Date: 15 Mar 2006 16:45:10 -0800 Subject: Markov process representation In-Reply-To: <44188597$1@nntp0.pdx.net> References: <44184edf$1@nntp0.pdx.net> <1142451735.430956.29110@j33g2000cwa.googlegroups.com> <44188597$1@nntp0.pdx.net> Message-ID: <1142469909.951143.253160@j52g2000cwj.googlegroups.com> try as i might i still get an error: File "markov.py", line 50 self._all_states |= set(key[i] for key in probabilities) I am running: Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin If that helps any... Thanks! From http Wed Mar 29 06:48:28 2006 From: http (Paul Rubin) Date: 29 Mar 2006 03:48:28 -0800 Subject: telnet session References: <1143632572.802412.6070@z34g2000cwc.googlegroups.com> Message-ID: <7xfyl1qxo3.fsf@ruckus.brouhaha.com> eight02645999 at yahoo.com writes: > When i purposely input a wrong password, it "hangs" at the login prompt > waiting for > login and Password. The host i am telnetting to is a unix server. > How can i "exit" this login prompt if the user keys in wrong password > in my script? It looks to me like after you send the wrong password, you send "ls" without checking that you got back another login prompt. Then the program hangs because both ends are waiting for input. Whatever your actual application is, try to avoid doing it this way. From onurb at xiludom.gro Tue Mar 14 04:16:17 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 14 Mar 2006 10:16:17 +0100 Subject: list/classmethod problems In-Reply-To: <1142285402.976178.17570@u72g2000cwu.googlegroups.com> References: <1142278756.690002.311210@v46g2000cwv.googlegroups.com> <1142285402.976178.17570@u72g2000cwu.googlegroups.com> Message-ID: <44168a15$0$18917$626a54ce@news.free.fr> ahart wrote: > Diez, Scott, and Bruno, > > I thank you all for your help and suggestions. I wasn't aware that > default values were considered class (static) values. These are *not* 'default values'. Defining a name in the body of a class statement bind that name to the *class*. To bind a name to the instance, you have to do it inside an instance method - usually in the __init__() method. Understand that there's not way to bind anything to an instance before you actually *have* an instance !-) > That seems a > little odd to me, Yes, it's very different from languages like Java or C++, but it makes perfect sens once you understand Python's object model. (snip) > Again, I thank you all. > You're welcome. -- 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 Mon Mar 13 05:04:59 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 13 Mar 2006 11:04:59 +0100 Subject: Cheese Shop: some history for the new-comers References: <44126523$0$1016$afc38c87@news.optusnet.com.au> Message-ID: A.M. Kuchling enlightened us with: > Given the endless whiny complaints about the name, though, I think > we should just give up and go back to PyPI (pronounced 'Pippy'). I love The Python Cheese Shop. It's original and distinctive. Besides that, it gives you more information that PyPI since Python is written fully. Not every name has to fully reflect the named. I mean, Microsoft is the largest software company on the planet, but no way that you can guess that from the name. 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 brian at rkspeed-rugby.dk Wed Mar 8 05:04:41 2006 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: Wed, 08 Mar 2006 11:04:41 +0100 Subject: Simple questions on use of objects (probably faq) Message-ID: Hi, I am struggling to understand how to really appreciate object orientation. I guess these are FAQ's but I have not been able to find the answers. Maybe my problem is that my style and understanding are influenced by matlab and fortran. I tried with the simple example below and ran into several questions: 1: Why can't I do: def __init__(self,self.x): and avoid the self.x=x 2: Is it a good idea to insert instances in a list or is there a simpler way to do something with all instances of a given type? 3: Why can?t I say and get the maximum of instance attributes and a list of them? y_max=max(y[].x) and ys=[y[].x] 4: Can I avoid the dummy counter i in the for loop and do something like: yz=[y[:-1].x-y[1:].x] The code that runs: class Foo: def __init__(self,x): self.x=x y=[] y.append(Foo(10.0)) y.append(Foo(110.0)) y.append(Foo(60.0)) ys=[] y_max=0.0 y_min=0.0 for s in y: ys.extend([s.x]) y_max=max(s.x,y_max) y_min=min(s.x,y_min) yz=[] for i in range(len(ys)-1): yz.append(ys[i+1]-ys[i]) What I hoped I could do: class Foo: def __init__(self,self.x): continue y=[] y.append(Foo(10.0)) y.append(Foo(110.0)) y.append(Foo(60.0)) ys=([y[].x]) y_max=max(y[].x) y_min=min(y[].x) yz=[y[:-1].x-y[1:].x] -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk From aleaxit at yahoo.com Sun Mar 26 02:19:54 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Mar 2006 23:19:54 -0800 Subject: Accessing func_name from inside a function References: <1143309619.566327.173640@j33g2000cwa.googlegroups.com> Message-ID: <1hcs34g.1f6lnx81ic59i5N%aleaxit@yahoo.com> Ben Finney wrote: > "James Thiele" writes: > > > I'd like to access the name of a function from inside the function. > > A function, like most other objects in Python, can have any number of > names bound to it without the object being informed. Any of those Yes, but, quite independent of the 0+ names BOUND to the object, function objects, like class and module objects, have ONE "true" name (which may or may not coincide with one of those bound to the object, if any) -- the special attribute __name__ (AKA func_name for function objects only, but I'll stick with __name__ which applies uniformly). Code in a module can get the module's name by simply accessing global variable __name__. I see nothing untowards in a desire to access __name__ from code within a function or a class body, getting the name of the function or the class respectively rather than the name of the module they're in... it's just not implemented that way (and can't be changed until Python 3.0 for backwards compatibility). But proposals for 3.0 can be entertained. Personally, I'd rather have a 3.0 keyword referring to "the current object" (module for module toplevel code, class for classbody toplevel code, function for code within a function) -- say for the sake of argument the keyword is 'current'; this would allow current.__name__ to have the obvious meaning, and would also allow a few more neat things (such as natural access to current.__doc__). But if the OP is looking for a Python 2.* solution, then sys._getframe or module inspect are the only way to go, be they "ugly" as he considers them, or not. Alex From http Thu Mar 2 20:39:27 2006 From: http (Paul Rubin) Date: 02 Mar 2006 17:39:27 -0800 Subject: do design patterns still apply with Python? References: <8SINf.1718$No6.40137@news.tufts.edu> <7x8xrs9xqb.fsf@ruckus.brouhaha.com> <7xirqwz5ye.fsf@ruckus.brouhaha.com> Message-ID: <7xu0agqpbk.fsf@ruckus.brouhaha.com> Roy Smith writes: > > Sandboxed code is a real obvious one. > What is "sandboxed code"? It's what the old rexec/bastion module tried unsuccessfully to implement: a way of running potentially hostile code while limiting the kinds of harmful stuff it can do. This is needed for things like browser applets. Javascript (not related to Java except by name) also depends on it. A web browser that let arbitrary web pages run python scripts would be totally insecure and would let the site implementers take over your browser. Obviously not every application needs this, but it's hard to do unless there's fairly deep support for it in the language. From pekka.niiranen at wlanmail.com Sun Mar 19 08:07:45 2006 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Sun, 19 Mar 2006 15:07:45 +0200 Subject: Python 2.5 Schedule In-Reply-To: <1142667600.257048.315910@z34g2000cwc.googlegroups.com> References: <1142667600.257048.315910@z34g2000cwc.googlegroups.com> Message-ID: <441d579f$0$25339$39db0f71@news.song.fi> Hi, what I would like to see in (www.python.org) is Windows installation package (*.msi) compiled with option "--enable-unicode=ucs4". See http://www.xml.com/pub/a/2005/06/15/py-xml.html -pekka- From dr.mtarver at ukonline.co.uk Mon Mar 20 13:32:41 2006 From: dr.mtarver at ukonline.co.uk (Mark Tarver) Date: 20 Mar 2006 10:32:41 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: <441ef3a2$0$15789$14726298@news.sunsite.dk> References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <441ef3a2$0$15789$14726298@news.sunsite.dk> Message-ID: <1142879561.174895.242180@g10g2000cwb.googlegroups.com> Interesting. But you probably need to post this as a new message, since it is a distinctly different problem from the one driving this thread. Mark From jbellis at gmail.com Mon Mar 20 01:12:01 2006 From: jbellis at gmail.com (Jonathan Ellis) Date: 19 Mar 2006 22:12:01 -0800 Subject: whats your favourite object relational mapper? In-Reply-To: <1142819539.741782.189420@v46g2000cwv.googlegroups.com> References: <1142801641.638791.148370@e56g2000cwe.googlegroups.com> <1142819539.741782.189420@v46g2000cwv.googlegroups.com> Message-ID: <1142835121.089445.236070@v46g2000cwv.googlegroups.com> Serge Orlov wrote: > Flavio wrote: > > With so many object relational mappers out there, I wonder which one is > > the preferred tool among the Pythonists... is there a favourite? > > > > Sqlobject, PyDO, SQLAlchemy, dejavu, etc... > > Google results: > Sqlobject ORM: about 17,100 > PyDO ORM: 469 > SQLAlchemy ORM: 571 > dejavu ORM: 659 ... which, of course, goes to show how stupid a metric this is, now that even Ian Bicking has admitted that SqlObject in its current form is a dead end. Personally, I think SqlAlchemy has the brightest future. It's significantly more sophisticated than the others, and it's already quite usable and even stable (if the 0.1.3 to 0.1.4 transition is any indication), although I think technically still alpha. -Jonathan From reinhold.strobl at gmail.com Thu Mar 9 05:01:25 2006 From: reinhold.strobl at gmail.com (reinsn) Date: 9 Mar 2006 02:01:25 -0800 Subject: How to dervie from an instance object? Message-ID: <1141898484.977839.4890@u72g2000cwu.googlegroups.com> Hi, I am currently working with ZopeX3. Because python doesn't include concept of interfaces, those were defined by the module zope.interface. So interfaces were defined like: class IMyInterface(zope.interface.Interface): ..... I have looked into the module zope.interface and found, that zope.interface.Interface is an object instance and no class object! But how does this work? How can I derive from an object instance? I mean is something like this possible in Python? class X: pass x = X() class Y (x): ..... Thanks for the replies in advance! From bignose+hates-spam at benfinney.id.au Mon Mar 27 17:38:14 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 28 Mar 2006 08:38:14 +1000 Subject: pysqlite References: <1143483441.697284.206720@u72g2000cwu.googlegroups.com> <1143484790.996231.232000@j33g2000cwa.googlegroups.com> <44284677$1_3@newspeer2.tds.net> <442849f0_1@newspeer2.tds.net> Message-ID: <87zmjbms2x.fsf@rose.polar.local> Kent Johnson writes: > Kent Johnson wrote: >> I sent pysqlite-2.0.4.win32-py2.4.exe > > Well tried, anyway, someone between OP and me is blocking zip and > exe attachements. Good thing too. Please don't send files as attachments in email; it enables the malware propagation system to continue, and there are better alternatives available. -- \ "What is it that makes a complete stranger dive into an icy | `\ river to save a solid gold baby? Maybe we'll never know." -- | _o__) Jack Handey | Ben Finney From gregtech at wp.pl Sat Mar 25 07:46:16 2006 From: gregtech at wp.pl (Grzegorz Smith) Date: Sat, 25 Mar 2006 13:46:16 +0100 Subject: MySQLDB - return strange type of variable Message-ID: <1j5qvk5e0u2o8.254nllrv5t1n$.dlg@40tude.net> Hi all. I'm trying get data from text field in MySQl 5.0 with my National characters. Data are stored in utf8 encodings. Here is the script: import MySQLdb, MySQLdb.cursors conn = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='profile_locale') c = conn.cursor(MySQLdb.cursors.DictCursor) c.execute("SET CHARACTER SET utf8") c.execute("SELECT string_value FROM lang_pl_pl WHERE id=8") row = c.fetchone() print row and i get: {'string_value': array('c', 'Zmie\xc5\x84 has\xc5\x82o')} where it come array type? How can i get value 'Zmie\xc5\x84 has\xc5\x82o' ?? because I trying do this and I can't achieve. If I do c.fetchone -shouldn't i get type tuple? I'm using MySQLdb 1.2.0 on Windows XP Professional SP2 installed Any help will be appreciated From deets at nospam.web.de Thu Mar 30 08:09:04 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 30 Mar 2006 15:09:04 +0200 Subject: does python could support sequence of short or int? References: <1143703009.628171.203020@i39g2000cwa.googlegroups.com> <1143715011.981884.136560@j33g2000cwa.googlegroups.com> <1143722234.988260.201690@t31g2000cwb.googlegroups.com> Message-ID: <4923n2Fmn935U1@uni-berlin.de> momobear wrote: > then how can I convert it to a int list? I read about struct and array, > I think they are not suitable, since I don't know how long will the > buffer is. I know if I write a plugins modules in C should works, but > that's really upset to tell to myself there is no way in Python. You think wrong - they _are_ suitable. You can create the struct.unpack-format string on the fly, which allows you to do this: import struct some_ints = range(1000) v = struct.pack("%ih" % len(some_ints), *some_ints) print struct.unpack("%ih" % len(some_ints), v) Regards, Diez From dbasch at yahoo.com Thu Mar 16 15:12:56 2006 From: dbasch at yahoo.com (Derek Basch) Date: 16 Mar 2006 12:12:56 -0800 Subject: Counting nested loop iterations Message-ID: <1142539976.631204.108260@u72g2000cwu.googlegroups.com> What is the best way to count nested loop iterations? I can only figure to use an index but that seems kludgy. index = 0 for animal in zoo: for color in animal: index += 1 Thanks, Derek Basch From bronger at physik.rwth-aachen.de Fri Mar 10 00:27:16 2006 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 10 Mar 2006 06:27:16 +0100 Subject: embedding Python: how to avoid memory leaks? References: <871wxbuaax.fsf@wilson.homeunix.com> <87pskvsr6y.fsf@wilson.homeunix.com> Message-ID: <87y7zij2dn.fsf@wilson.homeunix.com> Hall?chen! andrew at trevorrow.com (Andrew Trevorrow) writes: > Torsten Bronger wrote: > >> andrew at trevorrow.com (Andrew Trevorrow) writes: >> >>> [...] >>> >>> I couldn't get the PyRun_*File* calls to work on Windows, >>> presumably because of the FILE* problem mentioned in the docs. >> >> Which compiler do you use? > > MSVC++ (version 6 from memory -- I do most of my development on > the Mac and fire up Virtual PC occasionally to test Win builds). Well, I don't really *know*, but it's hard to believe to me that the file descriptor format changed within the Microsoft product series. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus ICQ 264-296-646 From max at alcyone.com Wed Mar 8 03:04:34 2006 From: max at alcyone.com (Erik Max Francis) Date: Wed, 08 Mar 2006 00:04:34 -0800 Subject: asynchat - operation could not complete w/ blocking In-Reply-To: References: Message-ID: Andreas R. wrote: > The problem I was having with push, is that is does not always send > complete packages. > > The solution to this was to use sendall() instead, but sendall() gives > blocking error messages. The purpose of asynchat's push methods is to queue outgoing data and send it when possible. When you're complaining that it does not always send complete packages, that strongly implies to me that you're misunderstanding how socket transmissions work. With TCP you're guaranteed that data will show up in the same order you sent it. You're not at all guaranteed that it will show up in the same chunks, or that you will get it all at the same time. The only time you'd want to do use something like "sendall" is when you really _do_ want to block until you make sure all the data is sent. So if you're wondering why it blocks, that suggests a deep misunderstanding in how TCP works. If you want to use asynchat to transmit data, all you need to do is set things up so that push handles them. Once that's the case, the data will be transmitted when the socket is writable such that it doesn't block. In other words, all you want to do is call push/push_with_producer and leave it at that. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Eppur, si muove! [But still it moves!] -- Galileo Galilei From tzot at sil-tec.gr Sat Mar 18 07:52:08 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Sat, 18 Mar 2006 14:52:08 +0200 Subject: Adding Multiple Attachments to SMTP mail (msg.add_header) References: <1141999717.849183.66640@p10g2000cwp.googlegroups.com> Message-ID: On 10 Mar 2006 06:08:37 -0800, rumours say that "EdWhyatt" might have written: >I attach my code for passing the information to msg.add_header: > >(AttNum = 2) > > for doatt in range(AttNum): > msg.add_header('Content-Disposition', 'attachment', >filename=ATTselection[doatt]) > doatt = doatt + 1 > outer.attach(msg) > >...... > body = MIMEText(Text) > outer.attach(body) > >Like I said, it is correctly sending the 2 seperate files from my >ATTselection array, but ultimately attaching the last file twice. The {doatt = doatt + 1} line is unneeded in the {for doatt in} loop. This *might* be your problem, I didn't delve any deeper. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From exhuma at gmail.com Mon Mar 20 09:39:47 2006 From: exhuma at gmail.com (exhuma.twn) Date: 20 Mar 2006 06:39:47 -0800 Subject: combining mod_python handlers publisher and psp problem In-Reply-To: <1142850953.288497.140930@t31g2000cwb.googlegroups.com> References: <1142843898.023725.73070@i39g2000cwa.googlegroups.com> <1142846505.248295.9100@u72g2000cwu.googlegroups.com> <1142850953.288497.140930@t31g2000cwb.googlegroups.com> Message-ID: <1142865587.725056.14950@i40g2000cwc.googlegroups.com> grahamd at dscpl.com.au wrote: > You could also have done: > > def index(req, name='John'): > s = 'Hello, there!' > if name: > names = ['a', 'b', 'c'] > s = 'Hello, %s!' % name.capitalize() > tmpl = psp.PSP(req, filename='index.psp') > req.content_type = 'text/html' > tmpl.run(vars = { 'greet': s, 'names': names }) > return > > Try the mod_python mailing list if you want an explaination of why. > > Graham Thanks, that worked. From brojohan at hotmail.com Wed Mar 29 13:22:21 2006 From: brojohan at hotmail.com (Bror Johansson) Date: Wed, 29 Mar 2006 20:22:21 +0200 Subject: instance and class-hierarchy ? Message-ID: <4901irFm4cgvU1@individual.net> Hi, I have a class-hierarchy (fairly deep and fairly wide). Is there a good and general way to test an instance-object obj for having a class belonging to a certain "sub-tree" of the hierarchy with a common parent class C? Testing for presence of attributes created at __init__ time is not considered general. Testing presence in the set of (manually enumerated) classes belonging to the "subtree" is not considered general. Testing like this: if C in [obj.__class__] + list_of_superclasses_to(obj.__class__): ... is general but I'm looking for a better way, if there is one. /BJ From irvine.david at gmail.com Sun Mar 19 16:39:58 2006 From: irvine.david at gmail.com (dirvine) Date: 19 Mar 2006 13:39:58 -0800 Subject: Pycrypto - active ?? Message-ID: <1142804398.710230.117640@j33g2000cwa.googlegroups.com> Does anyone know if pycrypto is active at all. I have been browsing groups etc. for some info and have found entries from 2003 (latest) regarding some bits I was looking for in particular reference to symmetrical encoding (AES) and auto padding and supply or not of iv to set up method i.e from Crypto.Cipher import AES from Crypto.Hash import SHA256 import random import zlib s = SHA256.new() s.update('secret') key = s.digest() x = AES.new(key, AES.MODE_CBC) # should be (key,AES.MODE_CBC,iv) iv should according to docs (which also look very old) should be a random number equal to the size of data blocks (in CBC or EBC). Does anyone know if by not supplying iv - is the data secure or not ?? Auto iv and auto padding would help this project a lot but unknown as to whether they exist. I may be missing an important point here though - so correct me where you will. It would appear to be a great shame if pyCrypto has stalled or not taken on board more seriously, there's great talk of implementing TLS, SSL etc. in the lists but little support of this visible in code or docs. The docs examples don't exist in code but getting them from ATTIC in cvs shows they are not stable, possibly not secure and not representative of the code now (and that's a couple of years ago) as an aside I have found a way to pad and remove padding at decrypt is quite simple, use zlib.compress -> pad -> encrypt then decrypt -> zlib.decompress and its just your data minus padding. From johnzenger at gmail.com Mon Mar 6 21:05:35 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 6 Mar 2006 18:05:35 -0800 Subject: Help - just a few lines of code needed References: <1141694360.291846.153820@v46g2000cwv.googlegroups.com> Message-ID: <1141697135.350106.238840@j33g2000cwa.googlegroups.com> There is some fine permutation code in the cookbook. Take a look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 . You can easily code something like: # xcombinations from the cookbook def xcombinations(items, n): if n==0: yield [] else: for i in xrange(len(items)): for cc in xcombinations(items[:i]+items[i+1:],n-1): yield [items[i]]+cc wordlist = ['HOUSE','jolly','---','0&','99'] for i in xrange(1, len(wordlist)+1): for g in xcombinations(wordlist, i): print "".join(g) > Unfortunately I am not able to program it myself, so > I would appreciate if someone could write this piece of > software, compile it (for DOS or Windows) and send the .exe file to: > > lory88 at gmail . com Meet us halfway, here. At least install Python. Also, it's a dangerous world out there. Don't run .exe s sent to you by people you don't know. From cjw at sympatico.ca Tue Mar 7 17:44:05 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 07 Mar 2006 17:44:05 -0500 Subject: Peter Naur wins ACM Turing Award In-Reply-To: <1141762342.250962.228770@j33g2000cwa.googlegroups.com> References: <1141713321.760459.66010@j33g2000cwa.googlegroups.com> <18fPf.157$xM2.46142@news20.bellglobal.com> <1141762342.250962.228770@j33g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: > Colin J. Williams wrote: > > >>Without detracting from the last sentence, I disagree. >> >>Peter Naur's honour is long overdue. >> >>Colin W. > > > Sometimes it's hard for me to figure out about what somebody else > disagrees with me in particular when I agree with him. Kay, You wrote: "That's very fine. Peter Naur has to be honored before he dies and Algol gets forgotten forever. Sarkasm mode off. Is it just me who thinks that this grand-old-man gala should be cancelled and replaced by a fields medal mode where the jury has to prove that it is a little more up to date? Maybe being at age of 50 would be good upper limit ( our societies grow older ;) This mode would enable to honor Simon Peyton Jones and Philip Wadler for Haskell and introducing monads to Haskell before the language is phased out in 20+ years." Perhaps I should have been careful to identify what I disagreed with. > > Is it possible that Peter Naur was forgotten when John Backus received > the Turing Award right in time in 1977? > > Kay > John Backus of IBM made a very different contribution with the development of the FORTRAN compiler. The Algol60 Report was more than BNF, although that was an important component. Best wishes, Colin W. From vincenzo.cacciatore at gmail.com Wed Mar 15 10:24:01 2006 From: vincenzo.cacciatore at gmail.com (LabWINC) Date: 15 Mar 2006 07:24:01 -0800 Subject: FIR filtering In-Reply-To: <47qph1Fgod1iU2@uni-berlin.de> References: <1142428703.224948.317700@u72g2000cwu.googlegroups.com> <1142435176.837718.42220@v46g2000cwv.googlegroups.com> <47qph1Fgod1iU2@uni-berlin.de> Message-ID: <1142436241.498689.266940@j52g2000cwj.googlegroups.com> I can't understand how gnuradio can help me... I find scipy is the only way to implement a good FIR. Thanks, Vincent From apardon at forel.vub.ac.be Mon Mar 13 04:33:39 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Mar 2006 09:33:39 GMT Subject: Why python doesn't use syntax like function(, , x) for default parameters? References: <44115054$0$14937$834e42db@reader.greatnowhere.com> <47df47Fd6rifU1@uni-berlin.de> <47dmiaFf5tgvU1@uni-berlin.de> Message-ID: Op 2006-03-10, Diez B. Roggisch schreef : >> Those default values are not 0 and , you may have >> only experience with situations where they behave as such but that >> is not the same. > > Well, it might be - but the conceptual behavior is (usually) the same. > >> If you need to know these values then you will need to know them >> just as much when a keyword is used or when the default values >> are used later. Calling >> >> f(3) or f(arg5=3) >> >> Will give you no more a clue about the missing default values >> than calling >> >> f(,,,,,3) >> >> At least in the last call you are given a clue about missing >> arguments. > > I didn't argue against that - I don't like the proposal, but I'm pretty > sure that it won't be accepted in any way whatsoever so I don't bother. You argued that f(,,3) would somehow be hard to figure out. > I just wanted to point out that you proclaim false evidence for a similar > situation already being part of python, and that thus the f(,,1) syntax was > justified. I didn't claim that the f(,,1) syntax was justified. I asked for an explanation about why something like f(,,3) would be hard to figure out. -- Antoon Pardon From fake at nospam.no Mon Mar 6 12:13:51 2006 From: fake at nospam.no (Blackbird) Date: Mon, 6 Mar 2006 18:13:51 +0100 Subject: %r References: <75-dnc5y7fLN-ZHZRVnzvA@telenor.com> Message-ID: Duncan Booth wrote: > Blackbird wrote: > >> [...] > >>>> a = 'I don\'t think so' >>>> print '%r' % a > "I don't think so" >>>> a = r'I don\'t think so' >>>> print "'%s'" % a > 'I don\'t think so' Excellent counterexample. Can something like this happen for other things than quotes? From roman.yakovenko at gmail.com Thu Mar 23 14:52:17 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 23 Mar 2006 21:52:17 +0200 Subject: boost python tutorial In-Reply-To: <1143141465.996635.232150@t31g2000cwb.googlegroups.com> References: <1143141465.996635.232150@t31g2000cwb.googlegroups.com> Message-ID: <7465b6170603231152x45b70369x5721f169f197f67f@mail.gmail.com> On 23 Mar 2006 11:17:46 -0800, MakaMaka wrote: > Hi, > I'm trying to build the basic boost.python tutorial that comes with the > distribution. I'm using bjam and mingw. It builds the module, but > upon import, it gives this error: > > ImportError: dynamic module does not define init function (inithello) > > I've found other threads with this problem as a topic, but no > solutions. Somebody has to have solved this.... > > > Any ideas? Yes. 1. You can subscribe to boost.python mailing list. 2. Can you check whether you named you module as hello? BOOST_PYTHON_MODULE(hello) > Thanks, > -Justin > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From novakps at gmail.com Sat Mar 4 09:19:29 2006 From: novakps at gmail.com (Paul Novak) Date: Sat, 4 Mar 2006 09:19:29 -0500 Subject: do design patterns still apply with Python? In-Reply-To: <7xk6bamxwo.fsf@ruckus.brouhaha.com> References: <8SINf.1718$No6.40137@news.tufts.edu> <7x8xrs9xqb.fsf@ruckus.brouhaha.com> <7xirqwz5ye.fsf@ruckus.brouhaha.com> <1141381499.859849.85900@p10g2000cwp.googlegroups.com> <7xk6bamxwo.fsf@ruckus.brouhaha.com> Message-ID: <21d803730603040619k22d04938i935118f1226e12b@mail.gmail.com> A lot of the complexity of design patterns in Java falls away in Python, mainly because of the flexibility you get with dynamic typing. For a Pythonic Perspective on Patterns, "Python Programming Patterns" by Thomas W. Christopher is definitely worth tracking down. It looks like it is out of print, but you can find used copies on Amazon. Regards, Paul. This sounds like an article crying out to be written, > > "(Learning) Design Patterns with Python". > > > > Has it been written already? > > > > Cheers, > > Terry > > > > Bruce Eckel began writing "Thinking In Python" it was last updated in > 2001. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From michaeltaft at gmail.com Tue Mar 14 19:57:00 2006 From: michaeltaft at gmail.com (mwt) Date: 14 Mar 2006 16:57:00 -0800 Subject: Little Help with Exceptions and ConfigParser In-Reply-To: <1142362024.653574.229370@j52g2000cwj.googlegroups.com> References: <1142362024.653574.229370@j52g2000cwj.googlegroups.com> Message-ID: <1142384220.206670.147590@j52g2000cwj.googlegroups.com> Whoops. Those page numbers are from "Cookbook." As well as the Except section in "Nutshell." Still stewing away here. ;) From caleb.hattingh at gmail.com Thu Mar 16 16:03:19 2006 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 16 Mar 2006 13:03:19 -0800 Subject: Binary python extensions with Free Pascal Compiler In-Reply-To: <1142542790.828105.76070@i40g2000cwc.googlegroups.com> References: <1142542143.010853.208920@z34g2000cwc.googlegroups.com> <1142542790.828105.76070@i40g2000cwc.googlegroups.com> Message-ID: <1142542999.213993.79450@p10g2000cwp.googlegroups.com> Well, there it is: * Added support for Free Pascal Compiler (http://www.freepascal.org/) and Lazarus Project (http://www.lazarus.freepascal.org/) Thanks to Michiel du Toit (micdutoit at hsbfn.com) That was easy. I just saw the new support for D2k6 recently. thx Ravi Caleb From python-url at phaseit.net Mon Mar 20 08:08:02 2006 From: python-url at phaseit.net (Peter Otten) Date: Mon, 20 Mar 2006 13:08:02 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 20) Message-ID: QOTW: "Anything with 'Python' in its name can't market Python well." - Iain Bicking "Who really cares whether NASA uses Python? One thing I learned from having to sit through too many software marketing presentations is that organizations like NASA are to software what the Library of Congress is to books." - Steven Lumos on comp.lang.ruby How would you compare two strings when you don't care about whitespace? Hint: no regular expressions needed. http://groups.google.com/group/comp.lang.python/browse_frm/thread/2ad8fae9cc32e333/b4dc3a17d7502391 Jarek Zgoda's hack seems to be the most reliable way to get localized month names. http://groups.google.com/group/comp.lang.python/browse_frm/thread/7d8e318b9b27a460/8b8283877bc02aa1?tvc=1 Python 2.5 is scheduled for August 19, 2006. Among the highlights are the with-statement simplifying reliable resource acquisition/release and Fredrik Lundh's ElementTree. When bugs due to clever workarounds made it into the standard library Guido finally gave in, so there will be an inline-if/else, too. Use with discretion :-) http://groups.google.com/group/comp.lang.python/msg/f6f95174484c24cc Experienced developers wrestle with thorny deployment issues. http://blog.ianbicking.org/packaging-python.html Is coding a text adventure? Matt Webb and his co-developers think so. They use Python as the tried and tested tool to explore new ideas. http://www.wired.com/news/technology/0,70413-0.html?tw=wn_technology_4 Iain Bicking shares his thoughts about the new python.org website and marketing Python. http://blog.ianbicking.org/python-marketing-2006.html You don't always need a big fat office suite to get your data out of an Excel spreadsheet. http://groups.google.com/group/comp.lang.python/browse_frm/thread/af8f5484123101ae/fd7fb0d4d894dce2?tvc=1 Stackless Python has been ported to Python 2.4.2. http://www.stackless.com/Members/rmtew/pycon2006Result ======================================================================== 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 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://python.sourceforge.net/peps/pep-0042.html 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 neurogasm at gmail.com Sat Mar 18 18:17:47 2006 From: neurogasm at gmail.com (Kevin F) Date: Sat, 18 Mar 2006 18:17:47 -0500 Subject: Getting .NET SDK to work with Python 2.4.2 In-Reply-To: References: <1142721716.734835.157980@z34g2000cwc.googlegroups.com> Message-ID: okay, i am new to python and realize that indentation is important. i have tried to put everything in their respective indentations but it still doesn't work, can someone try to fix this? from poplib import * server = POP3("mail.bluebottle.com") print server.getwelcome() print server.user("neurogasm at bluebottle.com") print server.pass_("xxxxxxxx") messagesInfo = server.list()[1] numMessages = len(messagesInfo) print numMessages emails = [] for msg in messagesInfo: msgNum = int(split(msg, " ")[0] msgSize = int(split(msg, " ")[1] if(msgSize < 20000): message = server.retr(msgNum)[1] message = join(message, "\n") emails.append(message) Kevin F wrote: > Dave wrote: >> I searched the usenet and some mail archives and tried various >> techniques, but I can't seem to get the .NET 2.0 SDK to work with >> python. I'm a total newbie when it comes to python installs. I >> downloaded the .NET 2.0 SDK and I have python 2.4.2 and im trying to >> install zope. So i go to the cmd and go to the directory and type >> "python setup.py build" (Will have to install after) and it comes up >> with this(after everything else runs smoothly): >> running build_ext >> error: The .NET SDK needs to be installed before building extensions >> for python. >> >> I set the .net2.0 directory in windows enviromental PATH and added a >> key to registry in: >> HKEY_{LOCAL_MACHINE}\Software\Microsoft\.NETFramework\FrameworkSDKDir >> to the path of it. It still doesn't recongnize it and I don't know why. >> > > okay, i am new to python and realize that indentation is important. i > have tried to put everything in their respective indentations but it > still doesn't work, can someone try to fix this? > > from poplib import * > > server = POP3("mail.bluebottle.com") > print server.getwelcome() > print server.user("neurogasm at bluebottle.com") > print server.pass_("hahaha") > > messagesInfo = server.list()[1] > numMessages = len(messagesInfo) > > print numMessages > > emails = [] > for msg in messagesInfo: > msgNum = int(split(msg, " ")[0] > msgSize = int(split(msg, " ")[1] > if(msgSize < 20000): > message = server.retr(msgNum)[1] > message = join(message, "\n") > emails.append(message) From mikael at isy.liu.se Thu Mar 9 08:34:24 2006 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 09 Mar 2006 14:34:24 +0100 Subject: accesibility of the namespace In-Reply-To: <1141909668.196271.295080@j33g2000cwa.googlegroups.com> References: <1141897375.385047.258520@j52g2000cwj.googlegroups.com> <1141909668.196271.295080@j33g2000cwa.googlegroups.com> Message-ID: Petr Jakes wrote: > Ooooops. My keyboard (fingers) was faster than my mind :( > So.... > There is more than one "run-time changed variable" in the dictionary > and not all strings in the dictionary are formatted using % operator. > Example: > lcd={ > 2:{2:(("Enter you choice"),("Your kredit= %3d" % (kredit)))}, > 4:{2:(("Your choice: %2s" % (keyboard)),("%-20s" % (actKeyboard)))}} > > I do not know which variable(s) to use for the % operator in the time > of the call of the value (% formatted string) from the dictionary. > > This is also the reason why the variable names are stored in the > dictionary with the strings. > > Any other suggestions? So, use something like >>> lcd={ 2:{2:("Enter you choice","Your kredit= %(kredit)3d")}, 4:{2:("Your choice: %(keyboard)2s" ,"%(actKeyboard)-20s")}} >>> kredit = 7 >>> keyboard = 'aa' >>> actKeyboard = 7654 >>> lcd[2][2][-1] % vars() 'Your kredit= 7' >>> lcd[2][2][0] % vars() 'Enter you choice' >>> lcd[4][2][0] % vars() 'Your choice: aa' >>> lcd[4][2][1] % vars() '7654 ' >>> HTH /MiO From gwill at wirelesstcp.net Fri Mar 3 13:10:55 2006 From: gwill at wirelesstcp.net (george williams) Date: Fri, 3 Mar 2006 10:10:55 -0800 Subject: Roundup Issue Tracker release 1.1.1 References: <200603031340.55177.richardjones@optushome.com.au> Message-ID: <000501c63eed$d0de2af0$c9b6d5cf@george0r1rrt3p> This all looks interesting but I don't know what all this would do for me and I don't understand any of it george ----- Original Message ----- From: "Richard Jones" To: Cc: ; Sent: Thursday, March 02, 2006 6:40 PM Subject: Roundup Issue Tracker release 1.1.1 > I'm proud to release this, the 1.1.1 release of Roundup. > > Fixed in this release: > > - failure with browsers not sending "Accept-Language" header > (sf bugs 1429646 and 1435335) > - translate class name in "required property not supplied" error message > (sf bug 1429669) > - error in link property lookups with numeric-alike key values (sf bug > 1424550) > - ignore UTF-8 BOM in .po files > - add permission filter to menu() implementations (sf bug 1431188) > - lithuanian translation updated by Nerijus Baliunas (sf patch 1411175) > - incompatibility with python2.3 in the mailer module (sf bug 1432602) > - typo in SMTP TLS option name: "MAIL_TLS_CERFILE" (sf bug 1435452) > - email obfuscation code in html templating is more robust > - blank-title subject line handling (sf bug 1442121) > - "All users may only view and edit issues, files and messages they > create" example in docs (sf bug 1439086) > - saving of queries (sf bug 1436169) > - "Adding a new constrained field to the classic schema" example in docs > (sf bug 1433118) > - security check in mailgw (sf bug 1442145) > - "clear this message" (sf bug 1429367) > - escape all uses of "schema" in mysql backend (sf bug 1397569) > - date spec wasn't allowing week intervals > > If you're upgrading from an older version of Roundup you *must* follow > the "Software Upgrade" guidelines given in the maintenance documentation. > > Roundup requires python 2.3 or later for correct operation. > > To give Roundup a try, just download (see below), unpack and run:: > > python demo.py > > Release info and download page: > http://cheeseshop.python.org/pypi/roundup > Source and documentation is available at the website: > http://roundup.sourceforge.net/ > Mailing lists - the place to ask questions: > http://sourceforge.net/mail/?group_id=31577 > > > About Roundup > ============= > > Roundup is a simple-to-use and -install issue-tracking system with > command-line, web and e-mail interfaces. It is based on the winning design > from Ka-Ping Yee in the Software Carpentry "Track" design competition. > > Note: Ping is not responsible for this project. The contact for this > project is richard at users.sourceforge.net. > > Roundup manages a number of issues (with flexible properties such as > "description", "priority", and so on) and provides the ability to: > > (a) submit new issues, > (b) find and edit existing issues, and > (c) discuss issues with other participants. > > The system will facilitate communication among the participants by managing > discussions and notifying interested parties when issues are edited. One of > the major design goals for Roundup that it be simple to get going. Roundup > is therefore usable "out of the box" with any python 2.3+ installation. It > doesn't even need to be "installed" to be operational, though a > disutils-based install script is provided. > > It comes with two issue tracker templates (a classic bug/feature tracker and > a minimal skeleton) and five database back-ends (anydbm, sqlite, metakit, > mysql and postgresql). > > -- > http://mail.python.org/mailman/listinfo/python-announce-list > > Support the Python Software Foundation: > http://www.python.org/psf/donations.html > > > -- > No virus found in this incoming message. > Checked by AVG Free Edition. > Version: 7.1.375 / Virus Database: 268.1.2/274 - Release Date: 3/3/2006 > From jstroud at ucla.edu Fri Mar 3 23:13:04 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 03 Mar 2006 20:13:04 -0800 Subject: stripping spaces in front of line In-Reply-To: <1141444890.389188.140870@i40g2000cwc.googlegroups.com> References: <1141444890.389188.140870@i40g2000cwc.googlegroups.com> Message-ID: eight02645999 at yahoo.com wrote: > hi > wish to ask a qns on strip > i wish to strip all spaces in front of a line (in text file) > > f = open("textfile","rU") > while (1): > line = f.readline().strip() > if line == '': > break > print line > f.close() > > in "textfile", i added some spaces in and then ran the code, it prints > out the lines without the spaces in front. I double checked "textfile" > and it does contains some lines with spaces in front. > Is it true that "readline().strip()" perform the removing of spaces in > front of a line as well? Is it documented anywhere? > I am using Windows environment. thanks > You have observed the expected behavior. If you only want the trailing spaces stripped, try "rstrip". If you only want the leading spaces stripped, try "lstrip". If you want no space anywhere try this: line = "".join(f.readline().split()) If you want to normalize space, do this: line = " ".join(f.readline().split()) This should fulfill 90% of your space-transforming requirements. James From johnjsal at NOSPAMgmail.com Sat Mar 11 00:07:10 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 11 Mar 2006 00:07:10 -0500 Subject: creating an executable? In-Reply-To: References: Message-ID: <8LqdnTRApMbexo_ZnZ2dnUVZ_s2dnZ2d@rcn.net> Larry Bates wrote: > John Salerno wrote: >> Well, now that I can time my laundry, I need to make it runnable. I >> tried looking for info on the freeze module in the help file, but it >> didn't seem to come up with much. According to the Python wiki, freeze >> is for making executables for Unix. >> >> Can I make an executable with just the standard distribution, or do I >> need a separate module? >> >> Thanks. > > You didn't ask about an installer, but I thought I'd make the suggestion > anyway. The combination of py2exe and Inno Installer works EXTREMELY > well for distributing software on Windows platform. Use py2exe to > create .exe and support files, use Inno to wrap it up into a neat single > setup.exe file for distribution. > > -Larry Bates Thanks. That's definitely something I would ask about eventually, so I'll check that one out too! From apardon at forel.vub.ac.be Tue Mar 28 02:45:09 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Mar 2006 07:45:09 GMT Subject: Difference between 'is' and '==' References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <1143462121.828462.34290@v46g2000cwv.googlegroups.com> <1143466119.249145.36960@i39g2000cwa.googlegroups.com> <48q9pfFlc8q0U1@uni-berlin.de> Message-ID: Op 2006-03-27, Donn Cave schreef : > In article <48q9pfFlc8q0U1 at uni-berlin.de>, > "Diez B. Roggisch" wrote: > ... >> So - your conclusion is basically right: use is on (complex) objects, not on >> numbers and strings and other built-ins. The exception from the rule is >> None - that should only exist once, so >> >> foo is not None >> >> is considered better style than foo == None. > > But even better style is just `foo' or `not foo'. Or not, > depending on what you're thinking. No it is not. When you need None to be treated special, that doesn't imply you want to treat zero numbers or empty sequences as special too. -- Antoon Pardon From johnjsal at NOSPAMgmail.com Wed Mar 8 23:50:57 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Mar 2006 23:50:57 -0500 Subject: advice on this little script In-Reply-To: <120vb889343kd1@corp.supernews.com> References: <2bSdncqWK7aJN5LZRVn-vA@rcn.net> <120vb889343kd1@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2006-03-09, John Salerno wrote: > >> from time import sleep >> >> minutes = input('Enter the number of minutes to wait: ') >> >> for x in range(minutes): >> sleep(1.0) >> minutes -= 1 >> print minutes, 'minutes remaining.' > > for x in range(minutes,0,-1): > sleep(60.0) > print minutes, 'minutes remaining' > I might be doing something wrong, but this just keeps printing out '10 minutes remaining' each time. From dbasch at yahoo.com Thu Mar 16 16:32:59 2006 From: dbasch at yahoo.com (Derek Basch) Date: 16 Mar 2006 13:32:59 -0800 Subject: Counting nested loop iterations In-Reply-To: <1142543729.818523.180560@i39g2000cwa.googlegroups.com> References: <1142539976.631204.108260@u72g2000cwu.googlegroups.com> <1142543729.818523.180560@i39g2000cwa.googlegroups.com> Message-ID: <1142544779.507177.150600@u72g2000cwu.googlegroups.com> Carl Banks wrote: > But even the clear version isn't as nearly clear and straightforward as > the nested fors with the counter. I wouldn't forsake that clarity just > so it isn't "kludgy". > > > Carl Banks Yeah, looks like using the counters is clearer. Thanks for the opinions everyone! Derek Basch From rrr at ronadam.com Mon Mar 20 15:39:18 2006 From: rrr at ronadam.com (Ron Adam) Date: Mon, 20 Mar 2006 14:39:18 -0600 Subject: ** Operator In-Reply-To: References: <1142833145.976550.104830@v46g2000cwv.googlegroups.com> <1142833540.860154.137040@u72g2000cwu.googlegroups.com> <1hcgw5p.1ufznwe1lxeagfN%aleaxit@yahoo.com> Message-ID: Christoph Zwerschke wrote: > Alex Martelli wrote: >> Sathyaish wrote: >> >>> I tried it on the interpreter and it looks like it is the "to the power >>> of" operator symbol/function. Can you please point me to the formal >>> definition of this operator in the docs? >> >> http://docs.python.org/ref/power.html > > I think this should be also mentioned in the Built-In Functions section > of the Library Reference. Probably most users do not read the Language > Reference (since the main menu says it's "for language lawyers" and yes, > it is not really fun to read). I agree and think the "for language lawyers" should be changed to something that encourages people to read it instead of encouraging them to avoid it. Maybe: "The Python language structure for everyone". If it's hard to read and understand, then that can and should be fixed. It probably should be moved to a position before the library reference manual and after the tutorial. Looking over the language reference manual will help in understanding the library reference manual I think. Cheers, Ron From neurogasm at gmail.com Mon Mar 20 02:23:06 2006 From: neurogasm at gmail.com (Kevin F) Date: Mon, 20 Mar 2006 02:23:06 -0500 Subject: IMAP Folder Size Information Message-ID: I'm trying to use the following code to get my remote server's folder size information. Unfortunately, i'm getting the error: Traceback (most recent call last): File "/Life/School/Homework/Spring 2006/OPIM 399/Tutorial/IMAP/mailboxsize.py", line 23, in -toplevel- number_of_messages_all += int(number_of_messages[0]) ValueError: invalid literal for int(): The requested item could not be found. What seems to be the problem? My code is here: import sys, os, string, imaplib, getpass imap_server = "webmail.xxxxx.xxxxx.edu" # Open a connection to the IMAP server M = imaplib.IMAP4_SSL(imap_server) M.login('xxxx', getpass.getpass()) # The list of all folders result,list = M.list() print "%-30s%5s%10s\n" % ("Folder", "# Msg", "Size") number_of_messages_all = 0 size_all = 0 for item in list[:]: x = item.split() mailbox = string.join(x[2:]) # Select the desired folder result, number_of_messages = M.select(mailbox, readonly=1) number_of_messages_all += int(number_of_messages[0]) size_folder = 0 # Go through all the messages in the selected folder typ, msg = M.search(None, 'ALL') # Find the first and last messages m = [int(x) for x in msg[0].split()] m.sort() if m: message_set = "%d:%d" % (m[0], m[-1]) result, sizes_response = M.fetch(message_set, "(UID RFC822.SIZE)") for i in range(m[-1]): tmp = sizes_response[i].split() size_folder += int(tmp[-1].replace(')', '')) else: size_folder = 0 print "%-30s%5d%10s" % (mailbox, int(number_of_messages[0]), size_folder); size_all += size_folder print "\n%-30s%5i%10.3f MB\n" % ("Sum", number_of_messages_all, size_all/1e6) # Close the connection M.logout() From kent at kentsjohnson.com Mon Mar 6 20:08:31 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 06 Mar 2006 20:08:31 -0500 Subject: Mixin class error In-Reply-To: References: Message-ID: <440cd84c_3@newspeer2.tds.net> Ed Leafe wrote: > In Dabo, we create cursor classes that combine the backend-specific > dbapi cursor class with our own mixin class that adds framework- > specific behaviors. This has been working well for a couple of years > now with many different backends, but today I'm getting errors with our > Firebird class. I've checked the kinterbasdb site, and found nothing > there that was helpful. The error reads: > > TypeError: Error when calling the metaclass bases > type 'kinterbasdb.Cursor' is not an acceptable base type > > Here's some simple code that will generate the error: > > import kinterbasdb > KCursor = kinterbasdb.Cursor > > class TestMixin(object): pass > # This next line will raise the error. > class CombinedCursor(TestMixin, KCursor): pass > myCursor = CombinedCursor() > > I'm not sure exactly what this error message means, so I don't know > how to go about fixing it. I have no clue but googling 'type is not an acceptable base type' finds this thread http://groups.google.com/group/comp.lang.python/browse_thread/thread/628b8ad34a36db17/579f716b143f4967%23579f716b143f4967?sa=X&oi=groupsr&start=0&num=3 which points to the Py_TPFLAGS_BASETYPE. This example http://www.python.org/doc/2.3.5/ext/node22.html shows that flag being set to indicate that an extension class may be subclassed; the API docs confirm this: http://docs.python.org/api/type-structs.html#l2h-968 So it looks like kinterbasdb.Cursor is a C extension class that may not be subclassed because Py_TPFLAGS_BASETYPE is not set. Whether this is by design or accident would be a question for the kinterbasdb developers. One workaround might be to use delegation instead of subclassing... Kent From lists at fabis-site.net Sun Mar 19 09:50:02 2006 From: lists at fabis-site.net (Fabian Steiner) Date: Sun, 19 Mar 2006 15:50:02 +0100 Subject: C-API: A beginner's problem Message-ID: I recently started learning C since I want to be able to write Python extension modules. In fact, there is no need for it, but I simply want to try something new ... I tried to implement the bubblesort algorithm in C and to use it in python; bubblesort.c compiles fine, but whenever I want to import the modul and call the function I get a segmentation fault. This is what the code looks like: static PyObject *py_bubblesort(PyObject *self, PyObject *args) { PyObject *seq = NULL, *item, *newseq = NULL; int seqlen, i; if(!PyArg_ParseTuple(args, "O", &seq)) { return NULL; } seq = PySequence_Fast(seq, "argument must be iterable"); if(!seq) { return NULL; } seqlen = PySequence_Fast_GET_SIZE(seq); int list[seqlen]; for (i = 0; i <= seqlen; i++) { item = PySequence_Fast_GET_ITEM(seq, i); list[i] = item; } bubblesort(list, seqlen); newseq = PyList_New(seqlen); if(!newseq) { return NULL; } for(i = 0; i < seqlen; i++) { PyList_SetItem(newseq, i, list[i]); } return newseq; bubblesort(int list[], int seqlen) is doing the actual job and it is working. What did I do wrong? As I am quite new to C, I probably made many mistakes, so please feel free to correct me. Cheers, Fabian From rjagodic at gmail.com Tue Mar 7 10:06:39 2006 From: rjagodic at gmail.com (Ratko Jagodic) Date: Tue, 7 Mar 2006 09:06:39 -0600 Subject: What version of python is running a script In-Reply-To: References: Message-ID: <1eb708be0603070706o22bf80ep34427a80a8ec3a11@mail.gmail.com> import sys sys.version yields something like: 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] On 3/7/06, Fernando Rodr?guez wrote: > > > Hi, > > How can my script tell which version of python is running it? > > Thanks > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexandre_irrthum at yahoo.com Thu Mar 2 06:16:14 2006 From: alexandre_irrthum at yahoo.com (alexandre_irrthum at yahoo.com) Date: 2 Mar 2006 03:16:14 -0800 Subject: puzzled by ImageDraw line Message-ID: <1141298173.961780.50370@v46g2000cwv.googlegroups.com> Hi there, I am puzzled by the comportment of the line function from the ImageDraw module with regard to the way it draws or does not draw the last pixel of a line. Below I test this function on a 3x3 image and show schematic representations of obtained images (where o means a drawn pixel) import Image, ImageDraw im = Image.new("L", (3,3)) draw = ImageDraw.Draw(im) draw.line((0,0,2,2), fill=255) im.save("test.tif") Gives: o-- -o- --- So the last pixel of the line is not drawn. Similarly, draw.line((0,2,2,0), fill=255) gives: --- -o- o-- And draw.line((1,0,1,2), fill=255) gives: -o- -o- --- But, surprisingly, draw.line((0,1,2,1), fill=255) gives: --- ooo --- Where the last pixel of the line -is- drawn, as I expected it would be for all lines. This seems to be true for various image sizes and line angles: the last pixel is never drawn unless the line is horizontal. Any clues ? Thanks alex From greg at cosc.canterbury.ac.nz Wed Mar 1 04:28:17 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 01 Mar 2006 22:28:17 +1300 Subject: PEP 354: Enumerations in Python In-Reply-To: References: <87accdplbj.fsf@rose.polar.local> Message-ID: <46l8jaFbnfgeU4@individual.net> Giovanni Bajo wrote: > What's the repr of an enumeration value? OTOH, it should be something like > "Weekdays.wed", so that eval(repr()) holds true. Also, it'd be very useful in > debug dumps, tracebacks and whatnot. That would be nice, but I don't think that's possible with what the PEP proposes, because in Weekdays = enum('mon', 'tue', etc...) there's no way for the enum object to know that it's meant to be called 'Weekdays'. A constructor argument could be added for this, but then you end up having to write the name twice, making the construct far less elegant. Maybe *this* is a good argument for making the enum object a class? Or maybe it's an argument for allowing decorators to operate on things other than functions, so you could write something like @enum Weekdays = ('mon', 'tue', etc...) -- Greg From ben at wintersun.org Mon Mar 20 18:03:44 2006 From: ben at wintersun.org (Ben Caradoc-Davies) Date: Tue, 21 Mar 2006 07:03:44 +0800 Subject: anonymous memory mapping In-Reply-To: References: <200603120149.22159.fabianosidler@gmail.com> Message-ID: <441f34d0$0$4681$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Fabiano Sidler wrote: > 2006/3/14, Fabiano Sidler : >>Ok, sorry! I wanted to do this: >> >>--- snip --- >>from mmap import mmap, MAP_ANONYMOUS >>mm = mmap(-1, 1024, MAP_ANONYMOUS) >>--- snap --- >> >>But I got an EnvironmentError, "[Errno 22] Invalid argument" (on >>Linux2.6, btw.). The reason why I want to use anonymous mapping is >>that it only allocates the memory it actually uses. > > Hello? Nobody out there who can answer this question? From the Linux mmap(2) man page: http://www.die.net/doc/linux/man/man2/mmap.2.html "You must specify exactly one of MAP_SHARED and MAP_PRIVATE." From the /usr/include/bits/mman.h: /* Sharing types (must choose one and only one of these). */ #define MAP_SHARED 0x01 /* Share changes. */ #define MAP_PRIVATE 0x02 /* Changes are private. */ /* ... later ... */ # define MAP_ANONYMOUS 0x20 /* Don't use a file. */ # define MAP_ANON MAP_ANONYMOUS The problem is that python mmap defaults to MAP_SHARED, but when you pass in (only) MAP_ANONYMOUS as the access parameter, you are silently unsetting the MAP_SHARED bit and not setting the MAP_PRIVATE bit. Linux wants to know which you want. With Python 2.4 on Linux 2.6, both work: from mmap import mmap, MAP_ANONYMOUS, MAP_SHARED, MAP_PRIVATE m1 = mmap(-1, 1024, MAP_ANONYMOUS|MAP_PRIVATE) # no error m2 = mmap(-1, 1024, MAP_ANONYMOUS|MAP_SHARED) # no error -- Ben Caradoc-Davies http://wintersun.org/ "Those who deny freedom to others deserve it not for themselves." - Abraham Lincoln From no-spam at no-spam-no-spam.com Sat Mar 18 13:08:41 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 18 Mar 2006 19:08:41 +0100 Subject: Python compiler In-Reply-To: References: <44195b7a$0$29204$8fcfb975@news.wanadoo.fr> <9akm12tr5o5dc319343560dl96sm2jo2fv@4ax.com> Message-ID: Rc wrote: > "DaveM" schreef in bericht > news:9akm12tr5o5dc319343560dl96sm2jo2fv at 4ax.com... > >>On Thu, 16 Mar 2006 13:34:14 +0100, "M?ta-MCI" >> wrote: >> >> >>>Apr?s, vous pourrez aussi fr?quenter le newsgroup : >>> fr.comp.lang.python >>>qui a l'avantage d'?tre en fran?ais. >> >>But perhaps he's a Flemish speaker - are you trying to start a riot? >> >>DaveM > > Yes,I'm a Flemish speaker, I have been to school in the evening > to study Englisch and also now for the last year I'm study French. > To improve my English it's maybe good to work with English > newsgroupes.I'm not looking for a riot,because I don't understand > the word.By the way, in case to learn Python,they told me it's > the most esay language to start. > But ,my question is when I start Python it is a Dos Window > that opened.I think it is not possible on a XP computer? > Or am I wrong. > Thanks by advances > Rc install Pythonwin (pywin32) for a GUI From fairwinds at eastlink.ca Wed Mar 1 21:55:00 2006 From: fairwinds at eastlink.ca (David Pratt) Date: Wed, 01 Mar 2006 22:55:00 -0400 Subject: Removing .DS_Store files from mac folders In-Reply-To: <1141267132.989375.71630@p10g2000cwp.googlegroups.com> References: <1141267132.989375.71630@p10g2000cwp.googlegroups.com> Message-ID: <44065E84.4070804@eastlink.ca> Hi Ben. Sorry about the cut and paste job into my email. It is part of a larger script. It is actually all tabbed. This will give you a better idea: for f in file_names: current_file = os.path.basename(f) print 'Current File: %s' % current_file # Clean mac .DS_Store if current_file == '.DS_Store': print 'a DS_Store item encountered' os.remove(f) Ben Cartwright wrote: > David Pratt wrote: > >># Clean mac .DS_Store >> if current_file == '.DS_Store': >> print 'a DS_Store item encountered' >> os.remove(f) > > ... > >>I can't figure why >>remove is not removing. > > > > It looks like your indentation is off. From what you posted, the > "print" line is prepended with 9 spaces, while the "os.remove" line is > prepended with a single tab. Don't mix tabs and spaces. > > Also, shouldn't that be "os.remove(current_file)"? > > --Ben > From s99999999s2003 at yahoo.com Fri Mar 31 09:52:35 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 31 Mar 2006 06:52:35 -0800 Subject: cgi error Message-ID: <1143816755.824662.116540@z34g2000cwc.googlegroups.com> hi I have a little function to use ftputil module to get a file from a server def getfile(filename): import ftputil host = ftputil.FTPHost(svr, usr,pswd) host.chdir("/somewhere") try: host.download(filename,filename,"a") except ftputil.FTPError,v: print v It works fine when i run it in python , but it won't run when i run my cgi script It says AttributeError: 'module' object has no attribute 'FTPHost' what could be a possible cause? thanks. From skip at pobox.com Tue Mar 21 13:12:16 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 21 Mar 2006 12:12:16 -0600 Subject: Encoding newlines in XML? In-Reply-To: References: <17440.4787.24186.25192@montanaro.dyndns.org> Message-ID: <17440.16896.506797.121479@montanaro.dyndns.org> Fredrik> I don't recommend putting non-trivial formatted stuff in Fredrik> attributes ... Yeah, I sort of knew that going in, but didn't want to make big changes to the code to do it in a cleaner fashion. I'll figure something out. Skip From deets at nospam.web.de Wed Mar 8 11:48:48 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 08 Mar 2006 17:48:48 +0100 Subject: Type Hinting vs Type Checking and Preconditions References: <1141835303.880207.18640@j52g2000cwj.googlegroups.com> Message-ID: <478gaiFe8hp8U1@uni-berlin.de> Tom Bradford wrote: > This type of hinting would only break type ducking in-so-much as a > function that leveraged that hinting would be looking specifically for > an instance of a particular type, which would be absolutely no > different than a developer performing the type check manually and > throwing it out if the type were invalid. It would otherwise just be a > lot of tedious and repetitive work for the developer. The thing with duck-typing is that exactly this kind of type-checking is _not_ what the developer is supposed to do. Doing so breaks duck-typing anyway, regardless of syntactic sugaring or not. Adding such a feature would immediately start people creating code that for example requires a list where an iterable would suffice - and thus eating from the usability of python in general. Diez From sjmachin at lexicon.net Thu Mar 23 14:53:01 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 24 Mar 2006 06:53:01 +1100 Subject: Remove integer from float number In-Reply-To: <4422FAA9.50506@websafe.com> References: <1143142664.507941.130240@g10g2000cwb.googlegroups.com> <4422FAA9.50506@websafe.com> Message-ID: <4422fcac@news.eftel.com> On 24/03/2006 6:44 AM, Larry Bates wrote: > Derek Basch wrote: > >>How can I return: >> >>".666" >> >>from float: >> >>"0.666" >> >>This is what I have so far: >> >> >>>>>"%.6f" % x >> >>Thanks Everyone, >>Derek Basch >> > > > This works but I'm not entirely sure I know what you are > trying to accomplish. > > ("%.3f" % x)[1:] > >>> x = 12345.666; ("%.3f" % x)[1:] '2345.666' >>> I'm sure of neither what the OP is trying to accomplish nor what Larry's definition of "works" is :-) Perhaps the condition abs(x) < 1.0 is implied ... From skip at pobox.com Sun Mar 12 14:57:55 2006 From: skip at pobox.com (skip at pobox.com) Date: Sun, 12 Mar 2006 13:57:55 -0600 Subject: New python.org site In-Reply-To: References: <1142094677.527237.322080@e56g2000cwe.googlegroups.com> Message-ID: <17428.32067.384432.728983@montanaro.dyndns.org> Steve> ... where do we go from there to get the winning design up on a Steve> server behind www.python.org? Hey, it's just a "Simple Matter of Programming"... Skip From neurogasm at gmail.com Sat Mar 25 16:24:32 2006 From: neurogasm at gmail.com (Kun) Date: Sat, 25 Mar 2006 16:24:32 -0500 Subject: using regex to pull out email addresses Message-ID: i have a regular expression that searches a string and plucks out email addresses however it doesn't work for email addresses w/a subdomain e.g. jon at home.jon.com emails = re.findall('(\w+@\w+\.\w+)', senderlist) <-- my code is there any way to modify that to include email addresses that also have subdomains? From TheExpert at ExpertHumor.com Fri Mar 31 00:55:24 2006 From: TheExpert at ExpertHumor.com (Expert Humor) Date: 31 Mar 2006 05:55:24 GMT Subject: <%><%><%><%>HOW TO BE FUNNY!<%><%><%><%> Message-ID: <786599533006@free.teranews.com> You too can learn to be funny in just 7 days flat: http://www.ExpertHumor.com/HowToBeFunny.htm *** Free account sponsored by SecureIX.com *** *** Encrypt your Internet usage with a free VPN account from http://www.SecureIX.com *** From sathyaish at gmail.com Mon Mar 20 03:16:35 2006 From: sathyaish at gmail.com (Sathyaish) Date: 20 Mar 2006 00:16:35 -0800 Subject: Chained Comparisons In-Reply-To: <441e607d$1@news.eftel.com> References: <1142835847.348629.177950@z34g2000cwc.googlegroups.com> <441e607d$1@news.eftel.com> Message-ID: <1142842595.057727.298380@z34g2000cwc.googlegroups.com> John, I did "guess" but I wasn't quite sure and so I asked. OK, I did not perform a search on the docs, but that was because: 1) It is easier to learn through an interactive medium like a forum; and 2) A search in the same document you are reading takes you "off" and "adrift", and as such, is equivalant to a task-switch, because you're already reading some material from the same help file and are stuck at some point. Thanks for the help. From julienfiore at gmail.com Thu Mar 23 04:21:54 2006 From: julienfiore at gmail.com (Julien Fiore) Date: 23 Mar 2006 01:21:54 -0800 Subject: Use of Python with GDAL. How to speed up ? In-Reply-To: <1143075460.471114.295930@e56g2000cwe.googlegroups.com> References: <1142590123.885456.67240@e56g2000cwe.googlegroups.com> <1142657313.334941.164870@i40g2000cwc.googlegroups.com> <1143020987.250993.16020@g10g2000cwb.googlegroups.com> <1143075460.471114.295930@e56g2000cwe.googlegroups.com> Message-ID: <1143105714.788185.224660@z34g2000cwc.googlegroups.com> Thank you Serge for this generous reply, Vectorized code seems a great choice to compute the distance. If I understand well, vectorized code can only work when you don't need to access the values of the array, but only need to know the indices. This works well for the distance, but I need to access the array values in the openness function. As regards array.array, it seems a bit complicated to reduce all my 2D arrays to 1D arrays because I am working with the gdal library, which works only with 'numeric' arrays. Julien From brian at rkspeed-rugby.dk Fri Mar 10 02:56:23 2006 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: Fri, 10 Mar 2006 08:56:23 +0100 Subject: Simple questions on use of objects (probably faq) References: Message-ID: Steven D'Aprano writes: > With this method in the class, your solution is easier than ever: Nice solution. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk From deets at nospam.web.de Wed Mar 8 06:35:44 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 08 Mar 2006 12:35:44 +0100 Subject: [exec cmd for cmd in cmds] References: Message-ID: <477tv5Fea6u8U1@uni-berlin.de> Sch?le Daniel wrote: > Hello all, > > >>> p = "z%i = complex(1-1e-%i, 1-1e-%i)" > >>> lst = [p % (i,i,i) for i in range(10, 30)] > >>> for item in lst: > ... exec item > ... > >>> > >>> p = "z%i = complex(1-1e-%i, 1-1e-%i)" > >>> lst = [p % (i,i,i) for i in range(10, 30)] > >>> [exec item for item in lst] > File "", line 1 > [exec item for item in lst] > ^ > SyntaxError: invalid syntax > >>> > > is this prohibited for some reasons or is this just happens to be > disallowed? exec is a statement. And statements aren' allowed in the _expression_ of a list-comprehension. > this is one more cool way > >>> p = "z%i = complex(1-1e-%i, 1-1e-%i);" > >>> c = reduce(lambda x,y: x+y, [p % (i,i,i) for i in range(20,30)]) > >>> exec c > > and one more :) > >>> p = "z%i = complex(1-1e-%i, 1-1e-%i);" > >>> c = "".join([ p % (i,i,i) for i in range(20,30) ]) > >>> exec c If you think so :) Ususally people go for dictionaries in such cases. Diez From steve at holdenweb.com Tue Mar 14 08:16:31 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 14 Mar 2006 13:16:31 +0000 Subject: wxPython Q? floating window In-Reply-To: <1142327307.197117.71320@i40g2000cwc.googlegroups.com> References: <1142327307.197117.71320@i40g2000cwc.googlegroups.com> Message-ID: mitsura at skynet.be wrote: > Hi, > > I have a question about wxPython. > On Windows systems, you can point your mouse over most items on your > desktop and a after a second or so, a small window will pop-up with > extra info about the thing your pointing at (try e.g. move your mouse > over the time in the right corner and a window will pop-up with the > date). > I was wondering this can be done with wxPython. I basically want to > create a wxTree object and when I point the mouse over the objects in > the tree I would like to have these kind of smal pop-up windows that > display more info about the object you are pointing at. > > Any help much appreciated. > See wxToolTip - you can set a tooltip with the SetToolTip method on most objects. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From bj_666 at gmx.net Sat Mar 18 17:18:40 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 18 Mar 2006 23:18:40 +0100 Subject: A Frame-space syntax ? - Re: global, globals(), _global ? References: <1hc8e79.imz7zd16x7t3sN%aleaxit@yahoo.com> <1hc97un.15qyd7bycer0fN%aleaxit@yahoo.com> <1hca6up.az5e3hn3t4iqN%aleaxit@yahoo.com> Message-ID: In , robert wrote: > The fact is: > * Python has that big problem with unnecessary barriers for nested frame > access - especially painfull with callback functions where you want to > put back data into the calling frame. You mean accessing the locals in the function that invoked the callback!? That sounds ugly. Makes it hard to decouple the caller and the callee here. Ciao, Marc 'BlackJack' Rintsch From frank at chagford.com Mon Mar 13 06:01:00 2006 From: frank at chagford.com (Frank Millman) Date: 13 Mar 2006 03:01:00 -0800 Subject: SSL/TLS - am I doing it right? In-Reply-To: <7xlkvehawp.fsf@ruckus.brouhaha.com> References: <1142240607.501914.4390@j52g2000cwj.googlegroups.com> <1142247180.180132.256110@v46g2000cwv.googlegroups.com> <7xlkvehawp.fsf@ruckus.brouhaha.com> Message-ID: <1142247660.337898.171550@z34g2000cwc.googlegroups.com> Paul Rubin wrote: > "Frank Millman" writes: > > I was hoping to avoid this step. The point of the exercise for me is > > encryption. I am not too worried about authentication. The next step in > > my app is for the client to enter a user id and password, and the > > server will not proceed without verifying this. > > That is a total disaster without authentication, since it means the > client can reveal the password to an imposter. Understood. You cannot have encryption without authentication - they go hand in hand. Back to the documentation. Thanks, Paul Frank From scott.daniels at acm.org Thu Mar 9 19:41:04 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 09 Mar 2006 16:41:04 -0800 Subject: Best way to have a for-loop index? In-Reply-To: <1141950744.482666.4430@j33g2000cwa.googlegroups.com> References: <1141950744.482666.4430@j33g2000cwa.googlegroups.com> Message-ID: <4410c919$1@nntp0.pdx.net> andrewfelch at gmail.com wrote: > I write a lot of code that looks like this: > > for myElement, elementIndex in zip( elementList, > range(len(elementList))): > print "myElement ", myElement, " at index: ",elementIndex > > > My question is, is there a better, cleaner, or easier way to get at the > element in a list AND the index of a loop than this? for elementIndex, myElement in enumerate(elementList): print "myElement ", myElement, " at index: ",elementIndex --Scott David Daniels scott.daniels at acm.org From brjohan at gmail.com Sun Mar 19 13:33:24 2006 From: brjohan at gmail.com (BrJohan) Date: Sun, 19 Mar 2006 19:33:24 +0100 Subject: Unpythonic? Impossible?? References: <485ep5Fij70mU1@individual.net> <441d8a74$1@nntp0.pdx.net> Message-ID: <485mfjFi9cf4U1@individual.net> "Scott David Daniels" skrev i meddelandet news:441d8a74$1 at nntp0.pdx.net... > BrJohan wrote: ... >> is it then possible to have this call: >> obj = A(data) >> return an instance of that particular class (e.g. class C3) in the >> hierarchy that - as decided by the __new__ functions - is the 'correct' >> one? >> >> A.__new__ could select between A, B1 and B2, while B1.__new__ could >> choose from B1, C3 and C4. >> >> I know how to use a class factory - and could work around using such a >> mechanism. However I am interested to know if I could let the classes do >> the work by themselves. > > Yes, it can be done. Yes, it is unclear (and hence UnPythonic). > The class factory _is_ the straightforward way to do this. The > following is the workaround (if you have to maintain A(...)): > > > class A(object): > def __new__(class_, *args, **kwargs): > if class_ is A: > if want_a_B1(*args, **kwargs): > return B1(*args, **kwargs) > elif want_a_B2(*args, **kwargs): > return B2(*args, **kwargs) > return object.__new__(class_) # Use *a,... except for object > > class B1(A): > def __new__(class_, *args, **kwargs): > if class_ is B1: > if want_a_B1(*args, **kwargs): > return B1(*args, **kwargs) > elif want_a_B2(*args, **kwargs): > return B2(*args, **kwargs) > return super(B1, class_).__new__(class_, *args, **kwargs) > > > --Scott David Daniels > scott.daniels at acm.org Agreed that the class factory method most often (maybe always) is the best one. For certain reasons, and in this particular case, I prefer the UnPythonic way. Sometimes it's good to have "more than one way to do it". It was the "return object.__new__(class_) " that I did not came to think of myself, that did it. Thank you for yor helpfulness. BrJohan From johnjsal at NOSPAMgmail.com Mon Mar 27 14:03:28 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 27 Mar 2006 19:03:28 GMT Subject: problems with looping, i suppose In-Reply-To: References: Message-ID: <4GWVf.1837$No6.41815@news.tufts.edu> John Salerno wrote: > Here's an exercise I was doing to guess a number from 1-100. Here's another question that is related: while True: year = raw_input('Enter year (or other character to quit): ') try: year = int(year) except NameError: break if (year % 4 == 0) and (year % 100 != 0 or year % 400 == 0): print year, 'is a leap year.\n' else: print year, 'is not a leap year.\n' raw_input() This works as expected, except that if you enter any character other than a number, the program just quits. Why doesn't it still execute the raw_input function and pause? I think this is what is happening in the other exercise too, but I don't know why. If you break out of the loop, should it still pause at raw_input? From reply.in.the.newsgroup at my.address.is.invalid Mon Mar 20 04:53:39 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 20 Mar 2006 10:53:39 +0100 Subject: Keeping a function from taking to long--threads? References: Message-ID: <3sus12pi9knpfirlvptmuqn2kf54o17tsq@4ax.com> : >I'm using windows, and from what I've tried, the setdefaulttimeout >function doesn't work on my machine. It should. It does on mine. -- Ren? Pijlman Wat wil jij leren? http://www.leren.nl From bdesth.quelquechose at free.quelquepart.fr Sun Mar 19 18:24:59 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 20 Mar 2006 00:24:59 +0100 Subject: Counting number of each item in a list. In-Reply-To: <7x8xr66y8b.fsf@ruckus.brouhaha.com> References: <1142772092.958602.272260@e56g2000cwe.googlegroups.com> <441d58f7$0$13046$626a54ce@news.free.fr> <1142774630.426660.19970@t31g2000cwb.googlegroups.com> <441d6342$1_3@newspeer2.tds.net> <441d9408$0$20430$636a55ce@news.free.fr> <441dab21$0$27059$626a54ce@news.free.fr> <7x8xr66y8b.fsf@ruckus.brouhaha.com> Message-ID: <441dbb6a$0$7108$626a54ce@news.free.fr> Paul Rubin a ?crit : > Bruno Desthuilliers writes: > >>And of course, I was right. My solution seems to be faster than Paul's >>one (but slower than bearophile's), be it on small, medium or large >>lists. >> >>nb: A is mine, B is Paul's and C is bearophile's, and the number after >>is the size of the list... > > > Interesting. I wonder if you could try it with a much larger number > of distinct values in the list. Please do, this could be interesting... From ptmcg at austin.rr._bogus_.com Thu Mar 30 09:21:08 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 30 Mar 2006 14:21:08 GMT Subject: re.I slowness References: <1143719899.018571.41330@u72g2000cwu.googlegroups.com> Message-ID: wrote in message news:1143719899.018571.41330 at u72g2000cwu.googlegroups.com... > We process a lot of messages in a file based on some regex pattern(s) > we have in a db. > If I compile the regex using re.I, the processing time is substantially > more than if I > don't i.e using re.I is slow. > > However, more surprisingly, if we do something on the lines of : > > s = > s = s.lower() > t = dict([(k, '[%s%s]' % (k, k.upper())) for k in > string.ascii_lowercase]) > for k in t: s = s.replace(k, t[k]) > re.compile(s) > ...... > > its much better than using plainly re.I. > > So the qns are: > a) Why is re.I so slow in general? > b) What is the underlying implementation used and what is wrong, if > any, > with above method and why is it not used instead? > > Thanks > Vikram > Can't tell you why re.I is slow, but perhaps this expression will make your RE transform a little plainer (no need to create that dictionary of uppers and lowers). s = makeReAlphaCharLowerOrUpper = lambda c : c.isalpha() and "[%s%s]" % (c.lower(),c.upper()) or c s_optimized = "".join( makeReAlphaCharLowerOrUpper(k) for k in s) or s_optimized = "".join( map( makeReAlphaCharLowerOrUpper, s ) ) Just curious, but what happens if your RE contains something like this spelling check error finder: "[^c]ei" (looking for violations of "i before e except after c") Can []'s nest in an RE? -- Paul From jantod at gmail.com Thu Mar 2 04:43:45 2006 From: jantod at gmail.com (jantod at gmail.com) Date: 2 Mar 2006 01:43:45 -0800 Subject: compare classes and not class instances Message-ID: <1141292625.252349.155580@e56g2000cwe.googlegroups.com> I not only want to compare class *instances* but also the classes themselves. Something like: class T(object): @classmethod def __cmp__(cls, other): return cmp(cls.__name__, other.__name__) @instancemethod def __cmp__(self, other): return cmp(self.x, other.x) class B(T): pass class A(T): pass sorted([B, A]) => [A, B] My motivation for doing so is simply to sort classes based on their names and not (as it seems is the default behaviour) on the order in which they were created. I guess I could always just do something like sorted(classes, key=lambda cls: cls.__name__)...but where's the fun in that? :-) From fabianosidler at gmail.com Tue Mar 14 07:57:00 2006 From: fabianosidler at gmail.com (Fabiano Sidler) Date: Tue, 14 Mar 2006 13:57:00 +0100 Subject: anonymous memory mapping In-Reply-To: References: <200603120149.22159.fabianosidler@gmail.com> Message-ID: 2006/3/14, Peter Hansen : > (As for me, I have no idea what the question is about, so this is the > most help I can give.) Ok, sorry! I wanted to do this: --- snip --- from mmap import mmap, MAP_ANONYMOUS mm = mmap(-1, 1024, MAP_ANONYMOUS) --- snap --- But I got an EnvironmentError, "[Errno 22] Invalid argument" (on Linux2.6, btw.). The reason why I want to use anonymous mapping is that it only allocates the memory it actually uses. Greetings, From felipe.lessa at gmail.com Fri Mar 17 20:39:46 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 17 Mar 2006 22:39:46 -0300 Subject: insert chars into string In-Reply-To: <1142645536.492888.216530@g10g2000cwb.googlegroups.com> References: <1142645536.492888.216530@g10g2000cwb.googlegroups.com> Message-ID: <1142645986.12460.13.camel@kenshin> Em Sex, 2006-03-17 ?s 17:32 -0800, eight02645999 at yahoo.com escreveu: > is there a string method to insert characters into a string? As far as I know, no. Strings are immutable in Python. That said, the following method may do what you want: def insert(original, new, pos): '''Inserts new inside original at pos.''' return original[:pos] + new + original[pos:] From duncan.booth at invalid.invalid Mon Mar 13 04:10:06 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Mar 2006 09:10:06 GMT Subject: __del__ not called? References: <84ee8$4415323b$506c2949$6059@news.chello.at> Message-ID: Gregor Horvath wrote: >> Of course, if your __del__ method actually does get invoked during >> program exit you have to be pretty careful what you do: the chances >> are any global variables you used in __del__ have already been >> destroyed in particular any modules you imported may have been >> deleted. In short, don't rely on anything much being possible from >> __del__ called this way. > > I wanted to close a database connection, which is opend by __init__. > > But what happens to my database connection (instance attributes of A) > when __del__ is never called? > First off, never depend on __del__ to do anything critical. The only guarantee about the __del__ method on an object is that it will be called zero, one, or more times. (Admittedly you have to work a bit to get it called more than once.) If you have a resource which absolutely must be tidied up, then always put the code which accesses that resource inside a try..finally construct. If it is something pretty global to your program than that try..finally might have to be at the outermost level of your program: try: main() finally: cleanup() (In Python 2.5 you will be able to use a 'with' construct instead, but unfortunately we still have to wait a bit for that to become common usage). Without knowing more about the specific database connection, I can't tell you what happens if you don't explicitly close it. I would hope that it will tidy itself up, but if your code keeps anything cached locally to be written out then obviously that might not get written. If the database supports transactions (and it should), then I would expect anything modified in a transaction which has been commited will be written correctly, and everything modified in a transaction which has not been commited will be discarded: closing (or not) the database should be pretty well irrelevant. From mapik.ua at gmail.com Fri Mar 10 08:31:49 2006 From: mapik.ua at gmail.com (mapik.ua at gmail.com) Date: 10 Mar 2006 05:31:49 -0800 Subject: open2 problem References: <1141994966.620846.99850@e56g2000cwe.googlegroups.com> Message-ID: <1141997509.152822.4660@z34g2000cwc.googlegroups.com> > Why don't you use the subprocess module? I have tried subprocess module and got the same problem From http Mon Mar 20 05:35:35 2006 From: http (Paul Rubin) Date: 20 Mar 2006 02:35:35 -0800 Subject: Pycrypto - active ?? References: <1142804398.710230.117640@j33g2000cwa.googlegroups.com> <1142807299.141313.306980@i40g2000cwc.googlegroups.com> <1142841321.980154.320340@u72g2000cwu.googlegroups.com> Message-ID: <7xslpdl7yg.fsf@ruckus.brouhaha.com> "dirvine" writes: > I just wonder if the project itself is active and more recent docs > exist to answer some of the questions I have posed. > > I certainly hope theres some answers. You mentioned TLS/SSL, so I hope you do know about . But that doesn't answer your immediate question about Pycrypto. From lycka at carmen.se Thu Mar 30 10:37:05 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 30 Mar 2006 17:37:05 +0200 Subject: Set Windows Environment Variable In-Reply-To: References: <1143723906.146263.136590@i40g2000cwc.googlegroups.com> Message-ID: Duncan Booth wrote: > Fuzzyman wrote: >> In the ``win32api`` package there is a ``GetEnvironmentVariable`` >> function, but no ``SetEnvironmentVariable``. Any options ? > > No, your only option is to find a solution which doesn't involve changing > another process's environment. Surely there must be a way to programatically set up the environment variables for not yet started processes? I.e. doing the same as when you manually change things in the control panel. I'm pretty sure many Windows installers do that, and while I suppose this is technically a registry manipulation, I suspect there is a more direct API somewhere. From roy at panix.com Thu Mar 2 21:01:07 2006 From: roy at panix.com (Roy Smith) Date: Thu, 02 Mar 2006 21:01:07 -0500 Subject: Question References: Message-ID: In article , "Tom Leggio" wrote: > Do I need this on my computer---Python---can I remove it without hurting > anything? > Thanks Tommy Tom, That's a very difficult question to answer without knowing more about your computer. Some systems depend on Python for administrative tasks. If you remove Python on such a system, you could create a mess for yourself. Why do you want to remove it? Even if you never use it, it's probably not taking up much space and it's not hurting anything. From jparlar at cogeco.ca Sun Mar 5 13:49:36 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Sun, 5 Mar 2006 10:49:36 -0800 Subject: Papers on Dynamic Languages In-Reply-To: References: Message-ID: On Mar 4, 2006, at 3:00 PM, Paul Boddie wrote: > > I'd have a look at the following Python-related papers: > > Michael Salib's Starkiller paper (and presentation): > http://www.python.org/pycon/dc2004/papers/1/ > > Mark Dufour's ShedSkin paper: > http://kascade.org/optimizing_python.pdf > > John Aycock's "Aggressive Type Inference" paper: > http://www.python.org/workshops/2000-01/proceedings/papers/aycock/ > aycock.html > > I also provided a fair number of references in the following thread: > > http://groups.google.co.uk/group/comp.lang.python/browse_thread/ > thread/cc98317bdf96efda > > I hope this is of use! > > Paul All that looks fantastic, and I'd forgotten there was a paper on Shedskin. Thanks a bunch, Jay P. From saint.infidel at gmail.com Fri Mar 31 11:00:55 2006 From: saint.infidel at gmail.com (infidel) Date: 31 Mar 2006 08:00:55 -0800 Subject: CGIHTTPServer threading problems In-Reply-To: References: Message-ID: <1143820855.139934.91260@j33g2000cwa.googlegroups.com> Alvin A. Delagon wrote: > I'm a simple python webserver based on CGIHTTPServer module: > > import CGIHTTPServer > import BaseHTTPServer > import SocketServer > import sys > import SQL,network > from config import * > > class > ThreadingServer(SocketServer.ThreadingMixIn,BaseHTTPServer.HTTPServer): > pass > > cfg = params() > print "XBOX Server started on port %s. Press Ctrl+C to kill Server" % > cfg.port > server = > ThreadingServer((cfg.name,cfg.port),CGIHTTPServer.CGIHTTPRequestHandler) > try: > while 1: > sys.stdout.flush() > server.handle_request() > except KeyboardInterrupt: > print "Server killed" > > > The my cgi scripts are stored in the cgi-bin folder. One cgi script in > particular implements multi-threading and is supposed to be asynchronous > but it's not working. The browser that requests on the cgi script tends > to wait until the cgi script is done. I checked multi-threaded cgi > script but I'm 100% percent sure that it has no problem since it worked > as a mod_python script before. Anyone came across with this problem? CGI doesn't run asynchronously. All you've done with a multithreaded CGI server is have each CGI script run on a separate thread. But that doesn't change the fact that a browser is going to sit there and wait as the CGI script runs to completion (which is how the server knows it's done). From tjreedy at udel.edu Tue Mar 14 14:45:56 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 14 Mar 2006 14:45:56 -0500 Subject: andmap and ormap References: <1142339035.687474.271120@p10g2000cwp.googlegroups.com> <1142339421.5045.3.camel@kenshin> Message-ID: "Joel Hedlund" wrote in message news:dv6e9h$28q$1 at news.lysator.liu.se... >> footnote: if you have a recent Python 2.5 build, > > Who would have that? Is it a good idea to use a pre-alpha python version? The pre-public release version compiles as 'alpha0'. I have the impression the current alpha0 is being kept closer to releaseable more of the time than used to be the case. For instance, the developers recently set up a buildbot system to compile and run all unit tests on several systems with a variety of hardware and OSes up to several times a day. The results are available at http://www.python.org/dev/buildbot/ At of minutes ago, 5 systems are green (ok), 1 orange (warn) , and 1 red (fail). > ... Or should I start grabbing the Subversion trunk on a nightly basis? 'Should' if you want to experiment with new features or test existing code now rather than later. I would only grab it when the tests pass on the system closest to yours, and only repeat when there is a reason to. Terry Jan Reedy From fredrik at pythonware.com Wed Mar 29 09:33:01 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 29 Mar 2006 16:33:01 +0200 Subject: Doc suggestions (was: Why "class exceptions" are not deprecated?) References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com><1143070060.384366.25480@z34g2000cwc.googlegroups.com><1143574346.354680.136060@i39g2000cwa.googlegroups.com><34bb7f5b0603290047o21b9a1b7k64cdd206f604fc10@mail.gmail.com> Message-ID: > btw, one alternative could be to use an infogame site for this purpose: > > http://infogami.com > > this gives you revision history, a permissions system (limiting editing to > registered users might be a good idea), comments, an associated blog, > voting, feeds, change logs, etc. alright, I got bored and uploaded a copy of the current Python tutorial to http://pytut.infogami.com From rrr at ronadam.com Sun Mar 19 03:18:02 2006 From: rrr at ronadam.com (Ron Adam) Date: Sun, 19 Mar 2006 02:18:02 -0600 Subject: Can I use a conditional in a variable declaration? In-Reply-To: <1142741039.554379.182170@g10g2000cwb.googlegroups.com> References: <1142741039.554379.182170@g10g2000cwb.googlegroups.com> Message-ID: volcs0 at gmail.com wrote: > I've done this in Scheme, but I'm not sure I can in Python. > > I want the equivalent of this: > > if a == "yes": > answer = "go ahead" > else: > answer = "stop" > > in this more compact form: > > > a = (if a == "yes": "go ahead": "stop") > > > is there such a form in Python? I tried playing around with lambda > expressions, but I couldn't quite get it to work right. I sometimes find it useful to do: answers = {True: "go ahead", False: "stop"} answer = answers[a == "yes"] This is also sometimes useful when you want to alternate between two values. values = {'a':'b', 'b':'a'} # define outside loop while 1: v = values[v] # alternate between 'a' and 'b' ... There are limits to this, both the keys and the values need to be hashable. Cheers, Ron From bdesth.quelquechose at free.quelquepart.fr Thu Mar 16 22:09:18 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 17 Mar 2006 04:09:18 +0100 Subject: how to get 20000 html pages content quickly from one server? In-Reply-To: <1142441926.525376.312030@i40g2000cwc.googlegroups.com> References: <1142439755.840346.181060@p10g2000cwp.googlegroups.com> <1142441572.689735.273320@j33g2000cwa.googlegroups.com> <1142441926.525376.312030@i40g2000cwc.googlegroups.com> Message-ID: <4419fbc1$0$13265$636a55ce@news.free.fr> JuHui a ?crit : > in fact, I want to do a script to get news on others site. Then ask the webmasters of theses sites if they do have a ress feed... From zhan0645 at yahoo.com Fri Mar 24 17:31:48 2006 From: zhan0645 at yahoo.com (Yanping Zhang) Date: Fri, 24 Mar 2006 14:31:48 -0800 (PST) Subject: Please help me to resolve this issue Message-ID: <20060324223149.29536.qmail@web52903.mail.yahoo.com> Hello everyone, I am pretty new in python. Please give me any idea about this issue: There is a function like this in my c dll: typedef void (WINAPI *myCallBack) (unsigned int myarg1, unsigned int myarg2) bool myfunc(myCallBack mycall) In my python code, I was able to access other functions in the dll, but I have no idea how to call myfunc() because of WINAPI argument. Thanks in advance. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From gene.tani at gmail.com Wed Mar 15 11:52:52 2006 From: gene.tani at gmail.com (gene tani) Date: 15 Mar 2006 08:52:52 -0800 Subject: how to get 20000 html pages content quickly from one server? In-Reply-To: <1142439755.840346.181060@p10g2000cwp.googlegroups.com> References: <1142439755.840346.181060@p10g2000cwp.googlegroups.com> Message-ID: <1142441572.689735.273320@j33g2000cwa.googlegroups.com> JuHui wrote: > Hi > I want to get 200000 html pages content from one server, you know > urllib.urlopen need construct network connection, it will be very > slowly, how to speed up this function? > I try to using multi-thread, it speed up, but I want to quickly more, > any idea about it? > Thanks! Bad: use backstreet Browser and see if your IP gets blacklisted good: ask permission From steve at REMOVEMEcyber.com.au Thu Mar 30 04:53:41 2006 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 30 Mar 2006 19:53:41 +1000 Subject: any() and all() on empty list? References: <442B9AF7.2010407@REMOVEMEcyber.com.au> <7xu09gicko.fsf@ruckus.brouhaha.com> Message-ID: <442BAAA5.8010009@REMOVEMEcyber.com.au> Paul Rubin wrote: > Steven D'Aprano writes: > >>Think of it this way: if all(seq) is true, shouldn't it be the case >>that you can point to a specific element in seq that is true? > > > No, all(seq) is true if you can't point to a specific element in seq > that's false. No, all(seq) is true if every element in seq is true. Surely that's a more intuitive definition than your definition by what you can't do. The question that needs to be answered is, what if there are no elements at all? That's an arbitrary decision. Like the question "what is 0**0?" in mathematics, some answers are more useful than others. I can respect that practical answer -- but it isn't the *only* answer. (For those who don't see why 0**0 is problematic, 0**x is equal to 0 for all x, and x**0 is equal to 1 for all x, so what do you do for 0**0?) Here's another way of looking at the problem: all(flying elephants which are pink) => true all(flying elephants which are not pink) => true So, these flying elephants -- are they pink or not? -- Steven. From kpvincent at hotmail.com Thu Mar 9 19:14:13 2006 From: kpvincent at hotmail.com (Kelly Vincent) Date: Thu, 09 Mar 2006 18:14:13 -0600 Subject: About printing in IDLE? In-Reply-To: Message-ID: >Installed Python 2.4.2 on Windows XP. >Activated IDLE. >Loaded the following to the Edit window: >--- >print "hello world" >for i in range(10): > print i, > >print "Done" >--- >It prints as: 0 1 2 3 4 5 6 7 8 9 Done >Should not Done be printed on a new line alone? >Thanks for any guidance. If you don't want the "Done" to print on the same line, you need to make sure that in the last iteration of the loop, you don't leave the trailing comma after the i. This would do the trick: for i in range(10): if i < 9: print i, else: print i print "Done" From tjreedy at udel.edu Sat Mar 11 12:15:06 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 11 Mar 2006 12:15:06 -0500 Subject: why "g".count('')==2 ? References: <1142079957.325348.248500@j52g2000cwj.googlegroups.com> Message-ID: For the same reason as >>> "".count("") 1 >>> "ab".count("") 3 This is counting slice positions, which is one more that the length of the string. From fredrik at pythonware.com Mon Mar 27 09:23:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 27 Mar 2006 16:23:25 +0200 Subject: XMLRPCServer issues References: <1143454964.071222.304540@e56g2000cwe.googlegroups.com> <1143467008.869965.50360@g10g2000cwb.googlegroups.com> Message-ID: "looping" wrote: > > 2. You might want to transmit integers as strings rather than use the > > XML-RPC integer type (which is limited to numbers between -2147483648 > > and 2147483647). > > Is it a limit of XML-RPC RFC or a limit (probably with a good reason) > of the python xmlrpclib ? the specification defines an integer field as a "four-byte signed integer". From martin at v.loewis.de Fri Mar 10 02:48:48 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 10 Mar 2006 08:48:48 +0100 Subject: embedding Python: how to avoid memory leaks? In-Reply-To: References: <441027d2$0$5025$9b622d9e@news.freenet.de> Message-ID: <44112F60.3020609@v.loewis.de> Andrew Trevorrow wrote: > Surely that's a bug that should be fixed. There should be some way > to tell Python "release all the memory you've ever allocated and > start again with a clean slate". This bug cannot be fixed in any foreseeable future. > I've been told that the next version of Python will release memory, > so that's good news. You can get it now if you're willing to build > Python from the latest source code. That still won't release all memory - only the arenas that don't have live Python objects on them anymore. Regards, Martin From sybrenUSE at YOURthirdtower.com.imagination Fri Mar 3 05:54:09 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 3 Mar 2006 11:54:09 +0100 Subject: help in converting perl re to python re References: <1141369650.346212.321410@i40g2000cwc.googlegroups.com> Message-ID: Joel Hedlund enlightened us with: > regexp = re.compile(r"<(tag1)>(.*)") I'd go for regexp = re.compile(r"<(tag1)>(.*?)") Otherwise this: line = "sometextothertext" match = regexp.search(line) will result in 'sometextothertext' 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 Fri Mar 24 02:12:53 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 24 Mar 2006 08:12:53 +0100 Subject: RELEASED Python 2.4.3, release candidate 1 References: <2773CAC687FD5F4689F526998C7E4E5FF1E617@au3010avexu1.global.avaya.com> Message-ID: Delaney, Timothy wrote: > However, there were definitely things found that were real bugs, and > subsequently fixed. absolutely. but a significant chunk of those bugs were in the "will leak references or access null pointers under extreme low-memory conditions, but it's not very likely that you get here if that's the case" category. still bugs worth fixing, of course, but I'd be a lot more worried if Coverity had dug up 96 "makes it easy to crash python, or to run user-provided code" errors... (also note that Coverity works on the C level only, so potential bugs that involves *using* Python C API stuff in odd ways are not always found) From nospam at nospam.com Thu Mar 9 15:07:18 2006 From: nospam at nospam.com (3c273) Date: Thu, 9 Mar 2006 12:07:18 -0800 Subject: timeit.py examples in docs generate error References: Message-ID: "Duncan Booth" wrote in message news:Xns9781C41BAEF48duncanbooth at 127.0.0.1... > Window's command processor doesn't recognise single quote marks as > meaning anything special, so your command is passing 4 separate arguments > to timeit.py instead of the 1 argument that a unix shell would be passing. > > Try using double quotes around everything instead: > > timeit.py "if hasattr(int, '__nonzero__'): pass" That did the trick. Thanks! Louis From ruby at no.spam Sat Mar 11 16:29:40 2006 From: ruby at no.spam (Michal Kwiatkowski) Date: Sat, 11 Mar 2006 22:29:40 +0100 Subject: Why property works only for objects? In-Reply-To: <1hc1abj.1fokrj9826uvjN%aleaxit@yahoo.com> References: <1hbyfgj.a3p39r1smomavN%aleaxit@yahoo.com> <4412107a$0$22499$636a55ce@news.free.fr> <1hbzzh7.1qlkv8hokpiqzN%aleaxit@yahoo.com> <1hc1abj.1fokrj9826uvjN%aleaxit@yahoo.com> Message-ID: Alex Martelli napisa?(a): >>>> obj.__dict__ > {} > > ...the presence of '__dict__' as an entry in C is confusing the issue, > because that's what you get in this case as obj.__dict__. It still bugs me. What's the actual procedure when doing attribute assignment? I understand it like this: obj.attr = value * if instance class has __setattr__, call it * else: if class has an attribute with name "attr" check if it's a descriptor; when it's overriding descriptor, call its __set__ method, otherwise raise AttributeError * else: bind "attr" as object attribute I've initialized C.__dict__ as plain dictionary, so it's not a descriptor. C also doesn't have __setattr__ method. I'm probably wrong, as __dict__ is considered somewhat special, but I can't really understand to which degree. Any other attribute I try to bind to object will be stored inside object dictionary, without looking up class dictionary. __dict__ is special, because it's *the* dictionary that stores all references to object's attributes. So, when assigning to __dict__ I would expect old dictionary to be simply replaced with this one. I don't understand why class attributes has any factor in this. > C.__dict__ gives you a dictproxy, not a real dict, by the way: > >>>> obj.__dict__ is C.__dict__['__dict__'] > True Why is that? I've initialized it as dictionary. When the type was changed and why? Is this used anywhere? > The funny thing is that builtins like var, which should know better, > also get fooled...: > >>>> vars(obj) > {} >>>> vars(obj) is C.__dict__['__dict__'] > True Docstring for vars says: With an argument, equivalent to object.__dict__. So this behavior simply conforms to the doc. > I think a fair case can be made that you've found a bug in Python here: > the existence of that __dict__ in C's class body is clearly causing > unintended anomalies. Fortunately, getattr and friends don't in fact > get confused, but vars does, as does assignment to obj.__dict__... What solution do you propose? 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 ianare at gmail.com Thu Mar 2 17:10:36 2006 From: ianare at gmail.com (=?iso-8859-1?B?aWFuYXLp?=) Date: 2 Mar 2006 14:10:36 -0800 Subject: string stripping issues References: <1141335954.481084.277030@p10g2000cwp.googlegroups.com> Message-ID: <1141337436.603446.58980@p10g2000cwp.googlegroups.com> from the python manual: strip( [chars]) The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped: >>> 'www.example.com'.strip('cmowz.') 'example' in your case since the letter 'H' is in your [chars] and the name starts with an H it gets stripped, but with the second one the first letter is a K so it stops there. Maybe you can use: >>> a[31:] 'Hughes. John\r\n' >>> b[31:] 'Kim, Dong-Hyun\r\n' but maybe what you REALLY want is: >>> a[31:-14] 'Hughes. John' >>> b[31:-14] 'Kim, Dong-Hyun' From plahey at alumni.caltech.edu Sun Mar 5 12:53:53 2006 From: plahey at alumni.caltech.edu (plahey at alumni.caltech.edu) Date: 5 Mar 2006 09:53:53 -0800 Subject: raw strings and \ In-Reply-To: References: <1141548565.145199.145910@e56g2000cwe.googlegroups.com> <1141576051.081203.318010@e56g2000cwe.googlegroups.com> Message-ID: <1141581233.526912.212360@z34g2000cwc.googlegroups.com> Hi Steven, thanks for the reply. I was/am aware that raw strings are mainly used for regular expressions (and franky that was I usually use them for). I was not aware that they still have "special powers" in raw strings (thanks for the link!). This one bit me when I was doing some quick and dirty hacking and a 5 minute task ended up being a much longer adventure becuase of this (Note to self: don't post when annoyed). From __peter__ at web.de Mon Mar 20 07:27:43 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 20 Mar 2006 13:27:43 +0100 Subject: Counting number of each item in a list. References: <1142772092.958602.272260@e56g2000cwe.googlegroups.com> <441d58f7$0$13046$626a54ce@news.free.fr> <1142774630.426660.19970@t31g2000cwb.googlegroups.com> <441d6342$1_3@newspeer2.tds.net> <441d9408$0$20430$636a55ce@news.free.fr> <441dab21$0$27059$626a54ce@news.free.fr> <1142856219.734122.299540@i40g2000cwc.googlegroups.com> Message-ID: per9000 wrote: > A good idea could be to change the header of the first one (if you want > the option to start counting from zero) into: > def dict_add(inlist,indict={},init=1): make that def dict_add(inlist, indict=None, init=1): if indict is None: indict = {} See "5. Mutable default arguments" at http://zephyrfalcon.org/labs/python_pitfalls.html for an explanation. Peter From this.address.is.fake at realh.co.uk Mon Mar 13 20:56:25 2006 From: this.address.is.fake at realh.co.uk (Tony Houghton) Date: Tue, 14 Mar 2006 01:56:25 +0000 (UTC) Subject: sizeof(struct timeval) References: Message-ID: In , Big and Blue wrote: > Big and Blue wrote: > > Tony Houghton wrote: > >> > >> How safe would I be assuming that > >> sizeof(struct timeval) == 2 * sizeof(long) > >> > >> is always true on Linux on different architectures? > > > > Based on what I was looking at today (well, yesterday now), you might > > be wrong. > > However, it looks as though I was wrong: [Snip headers showing my assumption is correct for his PC too] I've already looked at those headers too. But most of the definitions look like internal types and I'm not confident I can rely on them staying the same size. But I don't think there's a strong enough case for changing them to justify the glibc ABI change etc, so I'm probably safe. -- The address in the Reply-To is genuine and should not be edited. See for more reliable contact addresses. From sathyaish at gmail.com Mon Mar 20 05:46:37 2006 From: sathyaish at gmail.com (Sathyaish) Date: 20 Mar 2006 02:46:37 -0800 Subject: Chained Comparisons In-Reply-To: References: <1142835847.348629.177950@z34g2000cwc.googlegroups.com> <441e607d$1@news.eftel.com> <1142842595.057727.298380@z34g2000cwc.googlegroups.com> Message-ID: <1142851597.102623.321090@i40g2000cwc.googlegroups.com> >And firing up a news client, posting a message, and /waiting/ for a response isn't? In most cases, you could have read half the language reference manual in the time it takes to get an online response. No, it isn't because you continue reading the same stuff and you have the stuff open in another window at the same point you left reading it. That point is not lost. Posting a question in the newsgroup is like asking someone else; asking some other person to help you out and it works better than searching the documentation and loosing your train of thought. Besides, one doesn't stop reading the help file after posting a question on the newsgroup until the answer comes. The reading goes on. >and what exactly do you think the other people in the forum do? They go off and read the documentation so that they can be sure to quote it back accurately to you. So you've saved yourself the bother of looking up the docs just so that a large number of people can all do it for you. No, I see the people in this forum engage in trivia instead of understanding a beginner's anxiety, they engage in these flame wars on trivial issues. OK, let me calm down. People here are helpful, too. Python is a new language for me. I've been programming for over eight years now and have been there, done that on other forums where I saw a beginner. Sometimes, a few posts as a beginner can be a bitch. >I've tried reading this several times and can't make sense of what you are trying to say? http://www.joelonsoftware.com/articles/fog0000000022.html From gh at ghaering.de Thu Mar 30 10:30:29 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 30 Mar 2006 17:30:29 +0200 Subject: RELEASED Python 2.4.3, final. In-Reply-To: References: Message-ID: <442BF995.80104@ghaering.de> John Salerno wrote: > Anthony Baxter wrote: >>On behalf of the Python development team and the Python community, >>I'm happy to announce the release of Python 2.4.3 (final). > > Thanks! > >>Assuming no major bugs pop up, the next release of Python will >>be Python 2.5 (alpha 1), with a final 2.4.4 release of Python >>shortly after the final version of Python 2.5. > > Why would 2.4.4 come out after the final release of 2.5? Because upgrading to a higher Python micro release is always backwards-compatible. Even with existing third-party extension modules that you have installed. Going from 2.4.x to 2.5.x normally means you have to recompile all your extension modules written in C. Or download and install them, if they have binaries for your platform. -- Gerhard From claird at lairds.us Wed Mar 29 18:08:02 2006 From: claird at lairds.us (Cameron Laird) Date: Wed, 29 Mar 2006 23:08:02 GMT Subject: Seems like I want a pre-processor, but... References: <1143562487.421862.258860@u72g2000cwu.googlegroups.com> <1143564849.353889.169680@v46g2000cwv.googlegroups.com> Message-ID: In article <1143564849.353889.169680 at v46g2000cwv.googlegroups.com>, Russell Warren wrote: . . . >Anyway - it worked... you've answered my question perfectly, thanks. I >hadn't considered that the module loading phase could basically used >for preprocessing. You even helped by subtly providing a better >version checker... I didn't even know you could use < with a tuple like >that. I'll have to look into the logic rules there. . . . I'm working on an article on this topic, as it happens. Yes, in general pre-processors are strictly inferior for all realistic use-cases. Any time you think you need a pre-processor in Python, you should ask for help to learn of the better way that Python affords. Even while writing this, I realize that some people have implemented pre-processors for their Python, and expressed satisfaction with the result. The cases familiar to me had to do syntactic style--folks who don't like significant white space, and so on. From vinjvinj at gmail.com Fri Mar 24 10:16:59 2006 From: vinjvinj at gmail.com (vj) Date: 24 Mar 2006 07:16:59 -0800 Subject: What's the best way to learn perl for a python programmer? Message-ID: <1143213419.350106.274060@g10g2000cwb.googlegroups.com> I've been given a project which requires writing scripts that need to be run on over 3000 servers. Only about 15% of them have python installed on them. While all/most of them will have perl. I'll try and do as much as possible in pexpect but am sure I'll have do some significant perl. Any suggestions on what is the best way to get upto speed on perl? From bblais at bryant.edu Sat Mar 4 12:52:40 2006 From: bblais at bryant.edu (Brian Blais) Date: Sat, 04 Mar 2006 12:52:40 -0500 Subject: Python advocacy in scientific computation In-Reply-To: <1141436011.868907.292130@u72g2000cwu.googlegroups.com> References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> Message-ID: <4409D3E8.9050006@bryant.edu> sturlamolden wrote: > > Typically a scientist need to: > > 1. do a lot of experiments > > 2. analyse the data from experiments > > 3. run a simulation now and then > unless you are a theorist! in that case, I would order this list backwards. > > 1. Time is money. Time is the only thing that a scientist cannot afford > to lose. Licensing fees for Matlab is not an issue. If we can spend > $1,000,000 on specialised equipment we can pay whatever Mathworks or > Lahey charges as well. However, time spent programming are an issue. > (As are time time spend learning a new language.) > Another person stated that they don't have infinite funds, as implied here. I would add that, in addition to one's own research, professors must also teach and advise. I find it very helpful to be able to say to a student, "go download this, and here is the code I wrote for the work I do". The price is often an impediment for getting students into research. Often there are site licenses, but they don't work off campus. > 2. We don't need fancy GUIs. GUI coding is a waste of time we don't > have. We don't care if Python have fancy GUI frameworks or not. > again, for sharing ideas, GUIs are *necessary*. If you work with people who do less programming than you, then you need to make an interface to your code that they can understand. it doesn't have to be fancy, just functional. > 3. We do need fancy data plotting and graphing. We do need fancy > plotting and graphing that are easy to use - as in Matlab or S-PLUS. > here, I've found python to be good, but not great. matplotlib (pylab) is a really great thing, but is not as straightforward as plotting in Matlab. Either, you have a window which locks the process until you close it, or you do interactive mode, but the window results disappear if any other window is put on top (like your shell), and has to be manually redrawn. This makes it far less convenient to deal with in interactive mode. > 4. Anything that has to do with website development or enterprise class > production quality control are crap that we don't care about. > I think it can be pitched as an alternative to shell-scripts, which is a nice economy of concepts: the language you use for your scientific work, you can also use for your OS work, and your tinkering. > 7. "My simulation is running to slowly" is the number ONE complaint. > Speed of excecution is an issue, regardless of what computer science > folks try to tell you. That is why we spend disproportionate amount of > time learning to vectorize Matlab code. > here, I would plug Pyrex like crazy. to me the Python/Pyrex combination is the biggest selling point for me to convert my scientific matlab code to Python. Learning a new API is a drag, and I've found that SWIG is not particularly intuitive (although convenient, if you have a lot of libraries already written). Pyrex seems to get the best of all possible worlds: seamless use of python objects, and the ability to do C-loops for speed, with no API. Making extensions this way is a real joy. > Now please go ahead and tell me how Python can help me become a better > scientist. And try to steer clear of the computer science buzzwords > that don't mean anyting to me. > I have been using Matlab for nearly 10 years. My claim to no-fame is the neural network simulator Plasticity (http://web.bryant.edu/~bblais/plasticity) which has taken me years to write. I have some complaints about Matlab, but it has been a useful tool. Some of my complaints are as follows: 1) Cost. I find that the marketing model for Matlab is annoying. They nickle-and-dime you, with the base package (educational pricing) at $500 per machine/operating system/user and then between $200-$500 *per* "toolbox", which adds up really quick. I can't even buy 1 license for a dual boot, to have Matlab run on a Linux partition and a Windows partition. The cost impacts my use of Matlab in the classroom, and with research students. 2) License Manager. The license manager for Matlab is the most inconvenient program I have ever dealt with. It is incredibly sensitive to the license file, and it nearly impossible to debug. This has made Matlab one of the hardest programs to install, for me. The issue that impacts my productivity is the following: the license key is tied to the network card, on eth0. Thus, if I upgrade my laptop, I need to contact Mathworks for an updated license key. Also, occasionally, my operating system decides to name my wireless card eth0, and my wired card eth1. Nothing else is affected by this, but then I can't run Matlab! 3) Upgrade Version Hell. *Every* time Matlab has upgraded, my program has broken. Usually something small, but still it is a real pain in the butt. Also, I have to pay full price for the upgrade, or pay some fee continuously whether there is an upgrade or not. I have only been using Python for about 2 months, so I can't speak to some issues, but what does Python offer me? 1) Free (as in free beer). I've elaborated on this above. 2) Free (as in free speech). I like the fact that I am not burdened by having my projects tied to something proprietary. 3) Distribution ease. With py2exe, I can distribute on Windows systems which have no python installed. That's a real plus! 4) Clean programming environment. For teaching, it is nice to use a language which is so readable. 5) A huge number of built-in, or available, packages for nearly everything. 6) The ability to write portions of code in an optimized, as-fast-as-C, manner. 7) Relatively easy GUI frameworks I'm sure there are other things, but that's the way I am thinking right now. -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From nospamformeSVP at gmail.com Sat Mar 11 20:44:22 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Sat, 11 Mar 2006 20:44:22 -0500 Subject: Python IDE: great headache.... In-Reply-To: <1142120002.912902.69630@i40g2000cwc.googlegroups.com> References: <1142120002.912902.69630@i40g2000cwc.googlegroups.com> Message-ID: Sullivan WxPyQtKinter wrote: > IDLE is no longer satisfactory for me. Other IDEs make me very > confused. Really do not know which one to use. > > I use WinXP sp2 for current development. > > So far as I know, Eclipse + PyDev + PyDev Extension is perfect for > source code editing. Since I am really not sure how to use the debugger > module, I really do not know how to add watch to variables etc. Anyone > knows if this platform is a good one? > > I hope that an IDE should be featured with: > 1. Grammar Colored highlights. > 2. Manage project in a tree view or something alike, ie, a project file > navigator. > 3. Code collapse and folding. > 4. Code auto-completion: especially prompting function parameters when > I am typing a function previously defined by myself. Like the one in > Visual Studio series. > 5. Debugging: Breakpoints, conditional pause. watch for variables.step > into, over and out of a function. > What about other IDEs? Since I do not need GUI development. More over, > the free-of-charge IDE is highly preferred. > 6.Indentation management like in IDLE: press ctrl+[/] to modify the > identation of a line or a block. > Sullivan: Eclipse + Pydev does most, if not all, of your list - I am not sure what you mean by conditional pause - plus a whole lot more. One feature in particular that I don't think that I could live without is "Local History" which automatically maintains a series of revisions of each file whenever it is saved. This is coupled with a really nice built-in visual diff that allows you to look back on what changes you have made and restore them selectively. It is a bit like a built-in SVN or CVS system (which Eclipse also has) but at a very fine granularity and completely automatically. It allows you to be very agressive in making changes to files because it is so easy to wind the the clock back. I like Eclipse, but lots of folks on the Python groups seem to hate it with a passion. I think that the problem is that there are a lot of Eclipse concepts and terminology that you need to know before you can use it at all - it is puzzling to use right out of the box. This is compounded by the fact that the Eclipse documentation and tutorials are aimed at the Java programmer, and even so it still seems to be hard for Java programmers to get started in Eclipse. So it is even more difficult for Pythoneers. If you have used Eclipse for doing some Java work then Eclipse + Pydev is a snap, except that you keep looking for some of the wonderful features from the Java Editor that are not yet implemented in Pydev. If you have not used Eclipse for Java then you are likely to give up before you have discovered what it can do for you. If you install Eclipse and try to use it without reading the Workbench User Guide then you are not going to get anywhere. The one major missing Python feature in Pydev is an integrated Python Shell. Fabio has implemented a sort of shell in the debugger that allows you to enter Python statements in the console when you are stopped at a breakpoint - which is really nice. But you cannot use this in the traditional way to develop Python scripts. Don. From wolfgang.lipp at gmail.com Thu Mar 2 14:38:52 2006 From: wolfgang.lipp at gmail.com (_wolf) Date: 2 Mar 2006 11:38:52 -0800 Subject: re-posting: web.py, incomplete Message-ID: <1141328332.301456.238980@v46g2000cwv.googlegroups.com> hi all, this is a re-posting of my question i asked a month or so ago. i installed web.py, flups, and cheetah. when i copy'n'paste the sample app from then http://webpy.org homepage :: import web urls = ( '/(.*)', 'hello' ) class hello: def GET(self, name): i = web.input(times=1) if not name: name = 'world' for c in xrange(int(i.times)): print 'Hello,', name+'!' # point (1) if __name__ == "__main__": web.run(urls) it does seem to work *but* when i call it with sth like http://localhost/cgi-bin/webpyexample.py/oops?times=25 then the output is :: Hello, oops! Hello, oops! <20 lines omitted/> Hello, oops! Hel it is only after i insert, at point (1) as shown in the listing, :: print ( ( ' ' * 100 ) + '\n' ) * 10 ---print ten lines with a hundred space characters each---that i do get to see all twenty-five helloes. so, this is likely a character buffering problem. as far as i can see, it is a consistent amount of the last 32 characters that is missing from the page source. ok i thought so let's just output those 32 characters, :: print ' ' * 32 but *this* will result in a last output line that is 8 characters long, so someone swallows 24 characters. does look like a buffer of fixed length. i'd like to bust that ghost. _wolf From felipe.lessa at gmail.com Thu Mar 30 18:27:36 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Thu, 30 Mar 2006 20:27:36 -0300 Subject: how to comment lot of lines in python In-Reply-To: <1143760897.940841.285300@i39g2000cwa.googlegroups.com> References: <1143760897.940841.285300@i39g2000cwa.googlegroups.com> Message-ID: <1143761256.5172.0.camel@kenshin> Em Qui, 2006-03-30 ?s 15:21 -0800, diffuser78 at gmail.com escreveu: > Like in C we comment like > /* > Bunch of lines of code > */ > > Should we use docstring """ """ > > Or there is something else too ?? You should use a decent editor that could automatically comment/uncomment code upon your request. HTH, -- Felipe. From joel.hedlund at gmail.com Fri Mar 17 07:50:56 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Fri, 17 Mar 2006 13:50:56 +0100 Subject: Counting nested loop iterations In-Reply-To: References: <1142539976.631204.108260@u72g2000cwu.googlegroups.com> Message-ID: > for index, color in enumerate(color > for animal in zoo > for color in animal): > # the something more goes here. > pass I've been thinking about these nested generator expressions and list comprehensions. How come we write: a for b in c for a in b instead of a for a in b for b in c More detailed example follows below. I feel the latter variant is more intuitive. Could anyone please explain the fault of my logic or explain how I should be thinking about this? Or point me to somewhere where I can read up on this? Cheers, Joel Hedlund More detailed example: >>> c = [[1,4,8],[2,5,7]] >>> [a for b in c for a in b] [1, 4, 8, 2, 5, 7] >>> del a,b,c >>> c = [[1,4,8],[2,5,7]] >>> [a for a in b for b in c] Traceback (most recent call last): File "", line 1, in -toplevel- [a for a in b for b in c] NameError: name 'b' is not defined From danielmcbrearty at gmail.com Sun Mar 19 10:09:04 2006 From: danielmcbrearty at gmail.com (danielmcbrearty at gmail.com) Date: 19 Mar 2006 07:09:04 -0800 Subject: python newb has problem with import statements In-Reply-To: References: <1142761549.588654.223130@j33g2000cwa.googlegroups.com> Message-ID: <1142780943.965118.291380@i39g2000cwa.googlegroups.com> that was indeed the problem. Thanks! From johnjsal at NOSPAMgmail.com Tue Mar 28 15:19:26 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 28 Mar 2006 20:19:26 GMT Subject: tips for this exercise? Message-ID: I'm working on another exercise now about generating random numbers for the lottery. What I want to do is write a function that picks 5 random numbers from 1-53 and returns them. Here's what I have so far: numbers = range(1, 54) def genNumbers(): for x in range(5): fiveNumbers = [] number = random.choice(numbers) numbers.remove(number) fiveNumbers = fiveNumbers.append(number) return fiveNumbers Other than being sort of ugly, this also has the side effect of actually editing the original list, which I don't want since I will want to generate more than one set of numbers. Is there a better way to extract a certain number of items from a list (so maybe I don't need the for loop)? Is a list even the right type to use, since it gets edited in place? Perhaps a set? From dale at riverhall.nospam.co.uk Thu Mar 9 09:58:51 2006 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Thu, 09 Mar 2006 14:58:51 +0000 Subject: Python Evangelism References: Message-ID: Steve Holden wrote: > Any suggestions for improvement? > > regards > Steve Get rid of the scarey face? :-) -- Dale Strickland-Clark Riverhall Systems www.riverhall.co.uk We're recruiting. See the web site for details. From grante at visi.com Wed Mar 8 09:39:20 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 08 Mar 2006 14:39:20 -0000 Subject: Pyserial again References: <98ar02h8ikt6ub9hh09r4cv4hgujpelcgl@4ax.com> <120rqm12k3p31a@corp.supernews.com> <1141802777.131966.142950@e56g2000cwe.googlegroups.com> Message-ID: <120tr4opcgm74bc@corp.supernews.com> On 2006-03-08, luca72 wrote: > Belive me for a person of my age and my background ( i'm a > physics, but at my time no computer was allowed) all that for > you is simple, Believe me, it wasn't simple for us. We had to guess what you were doing wrong since you wouldn't show us your code. Something that could have taken a single post and response turned into an ordeal that lasted for days. -- Grant Edwards grante Yow! Didn't I buy a 1951 at Packard from you last March visi.com in Cairo? From msoulier at gmail.com Thu Mar 9 10:16:58 2006 From: msoulier at gmail.com (msoulier) Date: 9 Mar 2006 07:16:58 -0800 Subject: New python.org website In-Reply-To: <1141737431.437281.178860@z34g2000cwc.googlegroups.com> References: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> <1141737431.437281.178860@z34g2000cwc.googlegroups.com> Message-ID: <1141917417.970322.69030@e56g2000cwe.googlegroups.com> I don't mind the logo or the colour scheme, but I do mind the first paragraph in bolded text. What, you figure the readers can't figure out how to find "What is Python?" by themselves? Bold should be used sparingly. This is serious overuse. Otherwise, I like it. From scott.daniels at acm.org Tue Mar 14 13:31:56 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 14 Mar 2006 10:31:56 -0800 Subject: Python Debugger / IDE ?? In-Reply-To: <1142357338.313046.139060@i39g2000cwa.googlegroups.com> References: <1142357338.313046.139060@i39g2000cwa.googlegroups.com> Message-ID: <441709f1$1@nntp0.pdx.net> krypto.wizard at gmail.com wrote: > Is there any editor or IDE in Python (either Windows or Linux) which > has very good debugging facilites like MS VisualStudio has or something > like that. > > I like SPE but couldn't easily use winPDP. I need tips to debug my code > easily. > > Every help is greatly appreciated. > > Thanks > If you don't mind spending (not so much) money, ActiveState's Komodo is a nice debugger. With it you can even debug a Python program on a remote machine over a network connection (ideal for GUI problems). --Scott David Daniels scott.daniels at acm.org From greg.kujawa at gmail.com Thu Mar 9 12:28:41 2006 From: greg.kujawa at gmail.com (gregarican) Date: 9 Mar 2006 09:28:41 -0800 Subject: Timeout in xmlrpclib client call? Message-ID: <1141925321.067225.285060@j52g2000cwj.googlegroups.com> Looking at the docs for xmlrpclib I didn't see a way to pass a client call with an expressed timeout value. What is the easiest way to accomplish this? Do I have to tap into the underlying HTTP requests being sent? I want to build more try:except: error checking into my application and the app currently is blocking for the xmlrpclib client call. I could capture an HTTP connection timeout message or the like but was wondering if I could build something into the xmlrpclib call itself with a shorter timeout threshold. From ptmcg at austin.rr._bogus_.com Sun Mar 26 16:15:56 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 26 Mar 2006 21:15:56 GMT Subject: maximum() efficency References: Message-ID: "Steve R. Hastings" wrote in message news:pan.2006.03.26.17.26.36.252263 at hastings.org... > I was looking at a Python function to find the maximum from a list. > The original was more complicated; I simplified it. The built-in max() > function can replace the simplified example, but not the original. > > If you are interested in both the min and max values, here is an algorithm that performs only 3 comparisons for every 2 list items, instead of the brute force method's 4 comparisons. This walks the input list in pairs, compares the two items to each other, then compares the lesser with the current min and the greater with the current max. def minMax(L): lenL = len(L) if lenL == 0: return None,None if lenL == 1: return L[0],L[0] min_ = max_ = L[0] if lenL % 2: i = 1 else: i = 0 while i < lenL: a,b = L[i],L[i+1] if a > b: a,b = b,a if a < min_: min_ = a if b > max_: max_ = b i += 2 return min_,max_ Of course, this much Python bytecode is not near as fast as simply calling the builtins min() and max(). But, if you add psyco to the mix, things aren't so cut-and-dried. I tested this method using a list of randomly-generated strings, and after the list length exceeds 100-500 or so, minMax starts to outperform the compiled min() and max(). The following table shows the timing for the brute force min() and max() calls, followed by minMax(): List length 1: 0.0000229 0.0000612 List length 2: 0.0000056 0.0001081 List length 10: 0.0000059 0.0000707 List length 100: 0.0000154 0.0000087 List length 500: 0.0000589 0.0000534 List length 1000: 0.0001176 0.0000670 List length 10000: 0.0011485 0.0008954 List length 100000: 0.0126720 0.0077379 Using the OP's test of 1 million zeros with the first zero changed to a 1, here is the performance of minMax vs. min() and max(): List length 1000000: 0.1235953 0.0126896 minMax is 10X faster! Ironically, it's faster calling minMax() than either min() or max(). If your list contains objects that are expensive to compare, the crossover list length may be much shorter. -- Paul From bj_666 at gmx.net Wed Mar 15 17:10:16 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 15 Mar 2006 23:10:16 +0100 Subject: Tried Ruby (or, "what Python *really* needs" or "perldoc!") References: <1142355126.757569.42160@i40g2000cwc.googlegroups.com> <47obg1Fgjd6kU1@uni-berlin.de> Message-ID: In <47obg1Fgjd6kU1 at uni-berlin.de>, Diez B. Roggisch wrote: >> Yes, I'm trying to make time to look at the docutils code and the >> pydoc command to see what's involved. Unfortunately, my spare >> time is vanishingly close to zero right now. > > > You heard of epydoc? http://epydoc.sourceforge.net/ > > It pretty much does what you say I think - and for my personal projects I > use it. Maybe we an adopt it as standard-tool. Epydoc seems to be "dead" and pudge not yet alive: http://pudge.lesscode.org/ But it looks promising IMHO. Ciao, Marc 'BlackJack' Rintsch From robert.kern at gmail.com Sun Mar 5 00:00:15 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 04 Mar 2006 23:00:15 -0600 Subject: Python advocacy in scientific computation In-Reply-To: <1141436011.868907.292130@u72g2000cwu.googlegroups.com> References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> Message-ID: sturlamolden wrote: > Michael Tobis skrev: > > Being a scientist, I can tell you that your not getting it right. If > you speak computer science or business talk no scientist are going to > listen. Lets just see how you argue: I see we've forgone the standard conventions of politeness and gone straight for the unfounded assumptions. Fantastic. >>These include: source and version control and audit trails for runs, >>build system management, test specification, deployment testing (across >>multiple platforms), post-processing analysis, run-time and >>asynchronous visualization, distributed control and ensemble >>management. > > At this point, no scientist will no longer understand what the heck you > are talking about. All have stopped reading and are busy doing > experiments in the laboratory instead. Perhaps it sound good to a CS > geek, but not to a busy researcher. > > Typically a scientist need to: > > 1. do a lot of experiments > > 2. analyse the data from experiments > > 3. run a simulation now and then Being a one-time scientist, I can tell you that you're not getting it right. You have an extremely myopic view of what a scientist does. You seem to be under the impression that all scientists do exactly what you do. When I was in the geophysics program at Scripps Institution of Oceanography, almost no one was doing experiments. The closest were the people who were building and deploying instruments. In our department, typically a scientist would 1. Write grant proposals. 2. Advise and teach students. 3. Analyze the data from the last research cruise/satellite passover/earthquake. 4. Do some simulations. 5. Write a lot of code to do #3 and #4. There are whole branches of science where the typical scientist usually spends a lot of his time in #5. Michael Tobis is in one of those branches, and his article was directed to his peers. As he clearly stated. You are not from one of those branches, and you have different needs. That's fine, but please don't call the kettle black. > Thus, we need something that is "easy to program" and "runs fast > enough" (and by fast enough we usually mean extremely fast). The tools > of choice seems to be Fortran for the older professors (you can't teach > old dogs new tricks) and MATLAB (perhaps combined with plain C) for the > younger ones (that would e.g. be yours truly). Hiring professional > programmers are usually futile, as they don't understand the problems > we are working with. They can't solve problems they don't understand. I call shenanigans. Believe me, I would love it if it were true. I make my living writing scientific software. For a company where half of us have science degrees (myself included) and the other half have CS degrees, it would be great advertising to say that none of those other companies could ever understand the problems scientists face. But it's just not true. Scientists are an important part of the process, certainly. They're called "customers." Their needs drive the whole process. The depth and breadth of their knowledge of the field and the particular problem are necessary to write good scientific software. But it usually doesn't take particularly deep or broad knowledge to write a specific piece of software. Once the scientist can reduce the problem to a set of requirements, the CS guys are a perfect fit. That's what a good professional programmer does: take requirements and produce software that fulfills those requirements. They do the same thing regardless of the field. In my company, everyone pulls their weight, even the person with the philosphy degree. At that point, the CS skillset is perfectly suited to writing good scientific software. Or at least, any given CS-degree person is no less likely to have the appropriate skillset than a science-degree person. Frequently, they have a much broader and deeper skillset that is actually useful to writing scientific software. Most of the scientists I know couldn't write robust floating point code to save his life. Or his career. > What you really ned to address is something very simple: > > Why is Python better a better Matlab than Matlab? > > The programs we need to write typically falls into one of three > categories: > > 1. simulations > 2. data analysis > 3. experiment control and data aquisition > > (that are words that scientists do know) > > In addition, there are 10 things you should know about scientific > programming: > > 1. Time is money. Time is the only thing that a scientist cannot afford > to lose. Licensing fees for Matlab is not an issue. If we can spend > $1,000,000 on specialised equipment we can pay whatever Mathworks or > Lahey charges as well. However, time spent programming are an issue. > (As are time time spend learning a new language.) > > 2. We don't need fancy GUIs. GUI coding is a waste of time we don't > have. We don't care if Python have fancy GUI frameworks or not. Uh, time is money? Fighting unusable interfaces, GUI or otherwise, is a waste of resources. My brother works in biostatistics at the NIH. Every once in a while, the doctors he works for will ask him to do a particular analysis which requires him to use a particularly unusable piece of software. Every time, he has to spend half a day setting up the problem. This is why he's the one who gets to do it instead of the doctors. Now, he's considering rewriting the program in Python with a GUI that will essentially provide a Big Red Go Button (TM) so the doctors can do the analysis in a fraction of the time it takes now. > 3. We do need fancy data plotting and graphing. We do need fancy > plotting and graphing that are easy to use - as in Matlab or S-PLUS. > > 4. Anything that has to do with website development or enterprise class > production quality control are crap that we don't care about. There are quite a few scientists who are managing gigantic amounts of data, and run experiments/observations/whate-have-you so large that they need multi-institutional participation. Sharing that data in an efficient manner *does* require good dynamic websites and enterprise class software backing it up. There are more kinds of scientist in Heaven and Earth than are dreamt of in your philosophy. > 5. Versioning control? For each program there is only one developer and > a single or a handful users. I used to think like that up until two seconds before I entered this gem: $ rm `find . -name "*.pyc"` Okay, I didn't type it exactly like that; I was missing one character. I'll let you guess which. This is one thing that a lot of people seem to get wrong: version control is not a burden on software development. It is a great enabler of software development. It helps you get your work done faster and easier even if you are a development team of one. You can delete code (intentionally!) because it's not longer used in your code, but you won't lose it. You can always look at your history and get it again. You can make sweeping changes to your code, and if that experiment fails, you can go back to what was working before. Now you can do this by making copies of your code, but that's annoying, clumsy, and more effort than it's worth. Version control makes the process easier and lets you do more interesting things. I would go so far as to say that version control enables the application of the scientific method to software development. When you are in lab, do you say to yourself, "Nah, I won't write anything in my lab notebook. If the experiment works at the end of the day, only that result matters"? > 6. The prototype is the final version. We are not making software for a > living, we are doing research. I have lots of research code on my harddrive with decade-long changelogs that give the lie to that statement. If the code is useful now, it will probably still be useful in a few years. People will add to it, make suggestions, build on your work. This is how science is supposed to work. Practices which encourage this behavior are good things for science. > 7. "My simulation is running to slowly" is the number ONE complaint. > Speed of excecution is an issue, regardless of what computer science > folks try to tell you. That is why we spend disproportionate amount of > time learning to vectorize Matlab code. > > 8. "My simulation is running of of memory" is the number TWO complaint. > Matlab is notoriously known for leaking memory and fragmenting the > heap. > > 9. What are algorithms and data structures? Very few of us knows how to > use a datastructure more complicated than an array. That is why we like > Matlab and Fortran so much. Yes, and this is why you will keep saying, "My simulation is running too slowly," and "My simulation is running out of memory." All the vectorization you do won't make a quadratic algorithm run in O(n log(n)) time. Knowing the right algorithm and the right data structures to use will save you programming time and execution time. Time is money, remember, and every hour you spend tweaking Matlab code to get an extra 5% of speed is just so much grant money down the drain. That said, we have an excellent array object far superior to Matlab's. http://numeric.scipy.org/ > 10. We are novice programmers. We are not passionate programmers. We > take no pride in our work. The easier hack the better. We don't care if > we are doing OOP or not. However, we do hate complicated APIs or APIs > that look funny. We are used to seeing sin(x) in our calculus textbooks > and because of that we don't find Math.Sin(x) particularly elegant -- > even though Math.Sin(x) is more OOP and sin(x) clutters the global > namespace. > > Now please go ahead and tell me how Python can help me become a better > scientist. And try to steer clear of the computer science buzzwords > that don't mean anyting to me. 1. You will probably spend less time writing and running software. 2. If you play your cards right, more people will be able to use and improve your software. -- Robert Kern robert.kern at gmail.com "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From nid_oizo at yahoo.com_remove_the_ Wed Mar 1 12:13:59 2006 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Wed, 01 Mar 2006 12:13:59 -0500 Subject: Make staticmethod objects callable? In-Reply-To: References: <44055BE0.8030409@REMOVEMEcyber.com.au> Message-ID: Steven Bethard wrote: > ... > Yes, you have to explain descriptors, but at the point that you start > trying to do funny things with staticmethods and classmethods, I think > you need to start learning about them anyway.) That's all good points, but IMHO, descriptors are a much more advanced Python feature than static methods, especially for programmers from other backgrounds, like Java/C#/C++. We basically have the choice between hiding something unnecessarily complex or force to understand a useful feature;) > All that said, you should probably just submit a patch and see what > happens. I'll make a brief comment on it along the above lines, but > since I'm not a committer, it's not really worth your time to try to > convince me. ;) I might do it, but even if I'm not a commiter, I'll continue trying to convince myself;) Nicolas From aleaxit at yahoo.com Sun Mar 19 18:35:43 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 19 Mar 2006 15:35:43 -0800 Subject: cmp() on integers - is there guarantee of returning only +-1 or 0? References: <441dd94c$0$20108$834e42db@reader.greatnowhere.com> Message-ID: <1hcgdwr.zg61xysokadwN%aleaxit@yahoo.com> wrote: > Dmitry> doc says that it must be > 0, or < 0, but it seems that it > Dmitry> returns +1 or -1. Can it be reliably used to get the sign of x: > Dmitry> cmp(x, 0) like pascal Sign() function does? > > Why not > > def sign(n): > return n and n/abs(n) or 0 If you assume n is a number, the 'or 0' appears redundant (if you don't so assume, then the abs(n) and the division are doubtful;-). Alex From anne.nospam01 at wangnick.de Sat Mar 11 04:53:15 2006 From: anne.nospam01 at wangnick.de (anne.nospam01 at wangnick.de) Date: 11 Mar 2006 01:53:15 -0800 Subject: Inconsistency of special class method lookup? Message-ID: <1142070795.665106.10690@v46g2000cwv.googlegroups.com> Folks, I'm running into the following issue. A staticmethod of a class seems not to be accepted as a special class method of the class object itself. For example: class Foo(object): def __len__(): return 2 __len__ = staticmethod(__len__) print len(Foo) >>> Traceback (most recent call last): File "C:/Dokumente und Einstellungen/All Users/Dokumente/foo.py", line 4, in ? print len(Foo) TypeError: len() of unsized object However, the following works: class FooType(type): def __len__(self): return self.l() class Foo(object): __metaclass__ = FooType def l(): return 3 l = staticmethod(l) print len(Foo) >>> 3 Any good reason why the lookup process doesn't find __len__ as staticmethod of the class? Regards, Sebastian (posting using the account of my wife) From sjuranic at gmail.com Wed Mar 15 11:48:38 2006 From: sjuranic at gmail.com (Steve Juranich) Date: Wed, 15 Mar 2006 09:48:38 -0700 Subject: FIR filtering References: <1142428703.224948.317700@u72g2000cwu.googlegroups.com> <1142431475.577039.286470@e56g2000cwe.googlegroups.com> <1142437453.065363.309720@i40g2000cwc.googlegroups.com> Message-ID: LabWINC wrote: > If i type help scipy.filter it give me an error > > help scipy.filter > File "", line 1 > help scipy.filter > ^ > SyntaxError: invalid syntax You need parentheses: help(scipy.filter) -- Steve Juranich Tucson, AZ USA From rich at addr.invalid Tue Mar 7 17:44:56 2006 From: rich at addr.invalid (Rich) Date: Tue, 07 Mar 2006 23:44:56 +0100 Subject: Learning different languages Message-ID: Hi, (this is a probably a bit OT here, but comp.lang seems rather desolated, so I'm not sure I would get an answer there. And right now I'm in the middle of learning Python anyway so...) Anyway, my question is: what experience you people have with working with different languages at the same time? Actually I did myself many years ago, on my Commodore machines, where I programmed a lot in both basic, assembler and machine code, and don't recall I had any problems with handling these parallel. But then, they are very different languages, so it's not easy to get their syntax etc. mixed up with each other. I'm more thinking about Python, PHP, C++, Perl, Euphoria, which are languages I'm thinking of learning now. They look much more like each other than basic and MC, at places some even share the exact same syntax it seems, so your brain might get confused with what language you're actually working with? How is your experience with handling these paralell?. And what would you recommend - take one (or perhaps two) at a time, and then continue with the next? Or is it OK to go ahead with them all, at once? From joel.hedlund at gmail.com Tue Mar 28 04:35:31 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Tue, 28 Mar 2006 11:35:31 +0200 Subject: Difference between 'is' and '==' In-Reply-To: References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <4427d287$0$38669$edfadb0f@dread12.news.tele.dk> <1143529328.964467.132610@t31g2000cwb.googlegroups.com> Message-ID: >>You should _never_ use 'is' to check for equivalence of value. Yes, due >>to the implementation of CPython the behaviour you quote above does >>occur, but it doesn't mean quite what you seem to think it does. > > > /me not checking for value. I'm checking for identity. Suppose "a" is a > constant. I want to check if "b" is the same constant. /me too. That's what my example was all about. I was using identity to a known CONSTANT (in caps as per python naming conventions :-) to sidestep costly value equality computations. > By doing an "is" instead of a "==" you *can* catch some errors. > > By > testing with "is" you test for *that* integer, the one defined on your > module and that shouldn't go out of it anyway. I totally agree with you on this point. Anything that helps guarding against "stealthed" errors is a good thing by my standards. Cheers! /Joel Hedlund From bignose+hates-spam at benfinney.id.au Fri Mar 31 18:00:41 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 01 Apr 2006 09:00:41 +1000 Subject: Newbie: splitting dictionary definition across two .py files References: <1143766251.793448.191380@i40g2000cwc.googlegroups.com> <1143837982.398448.229550@u72g2000cwu.googlegroups.com> Message-ID: <87bqvm6wyu.fsf@rose.polar.local> "Karthik Gurusamy" writes: > Ben Finney wrote: >> That sounds like a very confusing architecture, and smells very >> much like some kind of premature optimisation. What leads you to >> that design? It's very likely a better design can be suggested to >> meet your actual requirements. > > So effectively I'm writing a python script as a poor man's make file. > [...] > I'm not really worried about optimizations at this time; just want a > cleaner solution to my problem. There is SCons, a much-improved build system written in Python, that may interest you. The build configurations are written in Python, so it seems to be quite similar to what you're currently working toward. -- \ "The reward of energy, enterprise and thrift is taxes." -- | `\ William Feather | _o__) | Ben Finney From larry.bates at websafe.com Sat Mar 25 20:48:23 2006 From: larry.bates at websafe.com (Larry Bates) Date: Sat, 25 Mar 2006 19:48:23 -0600 Subject: sending emails to a list of recipients [update] In-Reply-To: References: Message-ID: <4425F2E7.6030902@websafe.com> smtplib docs http://python.active-venture.com/lib/SMTP-example.html say that the to should be a list of addresses (your emails); s.sendmail(msg['From'], emails, msg.as_string()) -Larry Bates Kun wrote: > Kun wrote: >> i have the following code: >> >> ---------------------------------- >> import smtplib >> >> from email.MIMEText import MIMEText >> fp = open('confirmation.txt', 'rb') >> msg = MIMEText(fp.read()) >> >> From = 'xxxx at xxxx.xxxx.edu' >> >> msg['Subject'] = 'Purchase Confirmation' >> msg ['From'] = From >> msg['To'] = emails >> >> s = smtplib.SMTP('xxxx.xxx.xxx.edu') >> s.login('xxxxx','xxxx') >> s.sendmail(msg['From'], msg['To'], msg.as_string()) >> s.close() >> ---------------------------------- >> >> it works if msg['To'] = 'email at email.com' >> >> however, i'm trying to attach a list of emails named 'emails' to >> msg['To'] >> >> emails is in the following format: ['nxxx at gmail.com', >> 'nxxx at gmail.com', 'xxx at xxx.xxxx.edu'] >> >> >> anyone have an idea how i can modify this script to work with sending >> a list? note this is a snippet of a larger code, 'emails' is as a >> string defined earlier. > > this is my error msg of leaving the code in its current state... (brave > yourself) > > Traceback (most recent call last): > File "/Tutorial/IMAP/scannermailer.py", line 41, in -toplevel- > s.sendmail(msg['From'], msg['To'], msg.as_string()) > File > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/Message.py", > line 129, in as_string > g.flatten(self, unixfrom=unixfrom) > File > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/Generator.py", > line 82, in flatten > self._write(msg) > File > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/Generator.py", > line 120, in _write > self._write_headers(msg) > File > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/Generator.py", > line 166, in _write_headers > header_name=h, continuation_ws='\t').encode() > File > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/Header.py", > line 395, in encode > return self._encode_chunks(newchunks, maxlinelen) > File > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/Header.py", > line 355, in _encode_chunks > _max_append(chunks, s, maxlinelen, extra) > File > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/quopriMIME.py", > line 79, in _max_append > L.append(s.lstrip()) > AttributeError: 'list' object has no attribute 'lstrip' From bdesth.quelquechose at free.quelquepart.fr Sun Mar 5 18:29:52 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 06 Mar 2006 00:29:52 +0100 Subject: Separating elements from a list according to preceding element In-Reply-To: <1141587629.918414.245530@t39g2000cwt.googlegroups.com> References: <1141587629.918414.245530@t39g2000cwt.googlegroups.com> Message-ID: <440b49f0$0$12871$626a54ce@news.free.fr> Rob Cowie a ?crit : > I'm having a bit of trouble with this so any help would be gratefully > recieved... > > After splitting up a url I have a string of the form > 'tag1+tag2+tag3-tag4', or '-tag1-tag2' etc. The first tag will only be > preceeded by an operator if it is a '-', if it is preceded by nothing, > '+' is to be assumed. > > Using re.split, I can generate a list that looks thus: > ['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4'] > > I wish to derive two lists - each containing either tags to be > included, or tags to be excluded. My idea was to take an element, > examine what element precedes it and accordingly, insert it into the > relevant list. However, I have not been successful. > > Is there a better way that I have not considered? If you're responsible for the original URL, you may consider rewriting it this way: scheme://domain.tld/resource?tag1=1&tag2=1&tag3=1&tag4=0 Else - and after you've finished cursing the guy that came out with such an innovative way to use url parameters - I think the first thing to do would be to fix the implicit-first-operator-mess, so you have something consistent: if the_list[0] != "-": the_list.insert(0, "+") Then a possible solution could be: todo = {'+' : [], '-' : []} for op, tag in zip(the_list[::2], the_list[1::2]): todo[op].append(tag) But there's surely something better... From eric_brunel at despammed.com Tue Mar 28 02:18:01 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 28 Mar 2006 09:18:01 +0200 Subject: tkinter question References: <1143501305.697282.283180@t31g2000cwb.googlegroups.com> Message-ID: On 27 Mar 2006 15:15:05 -0800, wrote: > Hi > > I have a tkinter question. In the following script the window will not > display until the script has finished executing. It appears at the same > time as the output "script finished". How can I make it appear > immediately, with the output "script finished" appearing 5 seconds > later. > > cheers Dave > > from Tkinter import * > import time > > print "script started" > > top = Tk() > F = Frame(top) > F.pack() > Hello = Label(F, text="hello world") > Hello.pack() Here, the window is built with its contents, but the application is not started until you've done a top.mainloop() (or just mainloop()). This is required to be able to treat user requests. Until then, the window may actually not show up (depends on the platform, in fact). > time.sleep(5) Now you wait for 5 seconds, but the application is still not started. > print "script finished" > mainloop() Now the application starts and begins to treat user requests. What are you trying to do exactly? If you just want to automatically quit the application after 5 seconds, here is a way to do it (untested): -------------------------------------------- ## The script starts exactly as yours do from Tkinter import * print "script started" top = Tk() F = Frame(top) F.pack() Hello = Label(F, text="hello world") Hello.pack() ## Now, we'll register an event to call top.quit ## after 5 seconds (= 5000 milliseconds) top.after(5000, top.quit) ## Now we start the main loop top.mainloop() ## This should happen after top.quit() is ## executed by the event registered via after print "script finished" -------------------------------------------- HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" From aahz at pythoncraft.com Sun Mar 19 00:18:12 2006 From: aahz at pythoncraft.com (Aahz) Date: 18 Mar 2006 21:18:12 -0800 Subject: Have you ever considered of mousing ambidextrously? References: <1142660417.662387.73350@j33g2000cwa.googlegroups.com> Message-ID: In article , Roy Smith wrote: > >I never understood why people switch mouse buttons. I'm left handed, >so I put the mouse on the left side of my keyboard. It never occurred >to me to flip the buttons around. Heh. When possible, my work situation includes two computers, each with their own keyboard and mouse. To put the keyboards as close together as possible, the mice go on the outside. I generally flip the buttons on the left-hand mouse. That way I'm using the "same" fingers on both mice. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From scott.daniels at acm.org Wed Mar 8 10:43:09 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 08 Mar 2006 07:43:09 -0800 Subject: Type Hinting vs Type Checking and Preconditions In-Reply-To: <1141828474.684065.250070@j33g2000cwa.googlegroups.com> References: <1141826957.934692.289430@i40g2000cwc.googlegroups.com> <1141828474.684065.250070@j33g2000cwa.googlegroups.com> Message-ID: <440ef993$1@nntp0.pdx.net> Tom Bradford wrote: > Really what we're talking about here is weak typing in the form of > optional type hinting performed on a function by function basis.... Not what most of the world calls weak typing. > It is my feeling that this doesn't represent a sea-change in the way > Python does things, and it's certainly *not* the way things are done in > Java or C++, as both of those languages are strongly typed, wherein you > can't even pass a parameter if it isn't of the expected type, or a > subclass thereof. But I would call both of those languages weakly typed (and Python strongly typed). Any _correct_ type system must have contra-variant typing on results and co-variant typing on values. Java's type system breaks because it has decided to have arrays (which are both in and out, therefore "pinned" as to type) obey the subtype relationship of the elements of that array. So: array of truck-driver is a subtype of: array of driver and a procedure: procedure stores(driver[] arr, driver gus) arr[1] = gus Will type check as type-correct when passed a taxi-cab driver. I suspect such problems can be found in C++ as well, but I never hunted very hard. --Scott David Daniels scott.daniels at acm.org From nitrogenycs at web.de Thu Mar 9 13:48:56 2006 From: nitrogenycs at web.de (Matthias) Date: Thu, 09 Mar 2006 19:48:56 +0100 Subject: PyRun_String Message-ID: Hello, I encountered a strange problem today. I try to do this: Log("Marker 1"); Py_XDECREF( PyRun_String( "print 'Hi!'", Py_single_input, Dict, Dict) ); Log("Marker 2"); The output looks like Marker 1 Hi! Hi! Marker 2 Obviously Hi! is printed twice. I've extracted the above example of a more complex piece of code where you can clearly see that the statement is actually executed twice (not only printed). You can also see this with Log("Marker 1"); Py_XDECREF( PyRun_String( "def func():\n\ti = 0\n\twhile 1:\n\t\tyield i\n\t\ti += 1\no=func()", Py_file_input, Dict, Dict) ); Py_XDECREF( PyRun_String( "print o.next()", Py_file_input, Dict, Dict) ); Log("Marker 2"); Here the output goes Marker 1 0 1 Marker 2 What is the reason for this very strange behaviour? Did I do something wrong? -Matthias From paddy3118 at netscape.net Sat Mar 18 12:24:27 2006 From: paddy3118 at netscape.net (Paddy) Date: 18 Mar 2006 09:24:27 -0800 Subject: filter list fast In-Reply-To: <1142689630.989957.104200@p10g2000cwp.googlegroups.com> References: <1142675680.468064.167930@v46g2000cwv.googlegroups.com> <1142689630.989957.104200@p10g2000cwp.googlegroups.com> Message-ID: <1142702667.625459.151730@i39g2000cwa.googlegroups.com> What was the speed-up ? From dinko.tenev at gmail.com Tue Mar 21 04:51:17 2006 From: dinko.tenev at gmail.com (Dinko Tenev) Date: 21 Mar 2006 01:51:17 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1142589945.078364.32870@i39g2000cwa.googlegroups.com> <1142599685.186209.177630@j33g2000cwa.googlegroups.com> <1142612170.404220.23410@e56g2000cwe.googlegroups.com> <1142925259.468795.104500@t31g2000cwb.googlegroups.com> Message-ID: <1142934677.567529.272740@i40g2000cwc.googlegroups.com> wkehowski at cox.net wrote: > After the basic fact of generating the exclusion - a considerable > achievement - the program should be interactive. What if the target set > has thousands or millions of elements? There should be a loop-like way > ('do' in Haskell, for example) to peel off the elements one-by-one and > then terminate. Um..."interactivity" is a bit tricky in Prolog ;) As Geoffrey pointed out in his posting, the solutions are generated effectively one at a time. Following is a typical example of using the generator: generate_member( X, ... ), do_something_with( X ), fail. The underlying semantics is, roughly, 1) bind X, 2) do_something_with( X ), 3) fail, meaning reject this binding of X and backtrack. In this particular case, backtracking is tantamount to going back to 1). You can regard ( generate_member( X, ... ) ... fail ) as the equivalent of a loop construct, and do_something_with( X ) as the loop body. At any given time that the goal is being evaluated, there is only one binding for X in effect. On a side note, Haskell's "do" notation isn't really about loops. If you're referring to Tomasz's code, it's rather mapM_ that can sort of be thought of as looping through the list of values returned by generateNotMatching :) Cheers, Dinko From johnjsal at NOSPAMgmail.com Tue Mar 7 11:02:38 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 07 Mar 2006 16:02:38 GMT Subject: inserting into a list In-Reply-To: References: Message-ID: Christoph Haas wrote: > L[2:2]=[3] I'm still a little confused about this. If what I'm inserting is just an integer, why wouldn't L[2:2] = 3 work? What if you wanted to insert an actual list into that slot? Would you have to wrap it in double brackets? From max at alcyone.com Sun Mar 19 18:31:51 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 19 Mar 2006 15:31:51 -0800 Subject: Unpythonic? Impossible?? In-Reply-To: <7xu09u9fye.fsf@ruckus.brouhaha.com> References: <485ep5Fij70mU1@individual.net> <7xu09u9fye.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I remember having a similar problem involving multiple base classes > and deciding that factory functions couldn't do quite what I wanted. > Here's a thread about it, with a recipe using metaclasses by Roeland > Rengelink: > > http://tinyurl.com/rz6ne > > Unfortunately, the subtleties of what I was trying to do now escape > me. Your objection seemed to be that you'd prefer that you not have to have an explicit if/elif... (or lookup table) since that didn't seem very OO. Any solution that accomplishes this, whether it's a factory function, metaclasses, or a more traditional type of "virtual constructor" (your proposal at the end of your post, which is likely how you'd do it in C++) all need this. The short version of all this is all these approaches will work, are Functionally equivalent from the user's perspective, and all require upkeep, but some require more upkeep than others. In a dynamic language like Python, the best solution is the most straightforward one that requires the least upkeep. And that's a factory pattern. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Man is a hating rather than a loving animal. -- Rebecca West From scott.daniels at acm.org Sat Mar 18 22:22:23 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 18 Mar 2006 19:22:23 -0800 Subject: Have you ever considered of mousing ambidextrously? In-Reply-To: References: <1142660417.662387.73350@j33g2000cwa.googlegroups.com> <441c779a$1@nntp0.pdx.net> Message-ID: <441ccc26@nntp0.pdx.net> Roy Smith wrote: > In article <441c779a$1 at nntp0.pdx.net>, > Scott David Daniels wrote: > >> Roy Smith wrote: >>> I never understood why people switch mouse buttons. I'm left handed, so I >>> put the mouse on the left side of my keyboard. It never occurred to me to >>> flip the buttons around. >> Well, I switch 'em because the "forefinger is primary" is ingrained. > > I do both buttons with my forefinger. It just seems like the normal thing > to do. Ahhhh, but if you had been around when "chording" was practiced (a technique that makes no sense with less than 3 buttons), you would have been used to having to have pairs of buttons down at a time. With that style, it does make a difference which button the forefinger is over. -- -Scott David Daniels scott.daniels at acm.org From benji at benjiyork.com Thu Mar 30 13:09:49 2006 From: benji at benjiyork.com (Benji York) Date: Thu, 30 Mar 2006 13:09:49 -0500 Subject: Very stupid question. In-Reply-To: References: <1143739683.410001.118730@t31g2000cwb.googlegroups.com> <1143740072.340188.281730@i40g2000cwc.googlegroups.com> Message-ID: <442C1EED.5020709@benjiyork.com> On 3/30/06, *Sullivan Zheng* wrote: > Wow, seems I am not that supid. Why python does not include this > function in the file object. It is almost a tradition in other > languages... > really not elegant or OO. A file isn't an object. You can get a "file object" by opening a file (on disk), but it doesn't make much sense to have to open a file just to see how big it is. -- Benji York From jstroud at ucla.edu Fri Mar 10 16:17:17 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 10 Mar 2006 13:17:17 -0800 Subject: epydoc help (putting XML in docstrings) In-Reply-To: <1142023769.899027.114920@j33g2000cwa.googlegroups.com> References: <1142023769.899027.114920@j33g2000cwa.googlegroups.com> Message-ID: programmer.py at gmail.com wrote: > Hi everyone! I'm documenting some functions that return XML strings. > I'd like to have `sample' xml show up in my epydoc generated > documentation. However, epydoc does not like the indentation of the > XML and gives me this error -> > > L28: Error: Improper paragraph indentation. > > Here is a simple function that epydoc does not like: > > def test(): > """ > Return an XML string that looks like this:: > > > 123 > D > ... > > > @return: XML string. > """ > pass > > [jwyant at L-JWYANT:daplib]$ epydoc test.py > Importing 1 modules. > [.] > Building API documentation for 1 modules. > [.] > =========================================================================== > C:\cygwin\home\jwyant\code\dap-support\python\daplib\test.py > In test.test docstring (line 2): > --------------------------------------------------------------------------- > L5: Error: Improper paragraph indentation. > > Any ideas? > > Thanks! > Just indent the xml: def test(): """ Return an XML string that looks like this:: 123 D ... @return: XML string. """ pass James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From rridge at csclub.uwaterloo.ca Thu Mar 16 18:11:06 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 16 Mar 2006 15:11:06 -0800 Subject: recycling internationalized garbage References: <1141827739.823228.198160@j33g2000cwa.googlegroups.com> <1142349486.353020.194600@i39g2000cwa.googlegroups.com> <1142357837.655528.155460@j33g2000cwa.googlegroups.com> <441736A1.3090204@v.loewis.de> <1142409981.565148.314030@j52g2000cwj.googlegroups.com> <44191735.5080901@v.loewis.de> Message-ID: <1142550666.698719.99290@i39g2000cwa.googlegroups.com> Martin v. L?wis wrote: > So "valid" yes; "meaningful" no. Therefore, for all practical > purposes, 8-bit single-byte characters sets *will not* produce > byte sequences that are valid in UTF-8 (although they could - > it just won't happen). > > > In fact I can't think of any multi-byte encoding that can't produce > > valid UTF-8 byte sequence. > > The same reasoning applies for them. While you're reasoning may apply to European single-byte character sets, it doesn't apply as well to Far East multi-byte encodings. Take ISO 2202-JP (RFC 1468) for example where any string is valid UTF-8 as far as Python is concerned. About 1% of the EUC-JP encoded words and phrases listed in EDICT, a Japanese-English dictionary decode as valid UTF-8 strings. I get similar results with CEDICT, a Chinese-English dictionary, about 1% for the Big5 encoded version of the file and about 4.5% for the GB 2312 version. It would be nearly impossible to find all the strings in in Freedb that decode as UTF-8 but aren't really encoded in UTF-8, but they do exist. One example I managed to find are the GB 2312 encoded TTITLE5 and TTITLE13 records of disc id 020f5210. Ross Ridge From reply.in.the.newsgroup at my.address.is.invalid Fri Mar 10 06:18:46 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 10 Mar 2006 12:18:46 +0100 Subject: urlerror, urllib2: "no address" ... why or debug tips? References: <1141963555.362124.38520@j52g2000cwj.googlegroups.com> Message-ID: <42o2129mhscimmklievbku743mbjmbrsus@4ax.com> joemynz at gmail.com: >Help please with a URLError. Post your code (a small self-contained example, preferrably) and the URL. -- Ren? Pijlman From jmbc at nospam.fr Fri Mar 3 09:33:34 2006 From: jmbc at nospam.fr (jean-michel bain-cornu) Date: Fri, 03 Mar 2006 15:33:34 +0100 Subject: how to write file with cp1250 encodings? In-Reply-To: <1naixxfnequd.pr3wbg48tvap$.dlg@40tude.net> References: <1naixxfnequd.pr3wbg48tvap$.dlg@40tude.net> Message-ID: <440853c2$0$1148$7a628cd7@news.club-internet.fr> Hi, Grzegorz Smith wrote: > Hi all. I have got situation: i load data from database(MSSQL) wchich are > encoded cp1250 and I fill template with that data (Cheetah Template), after > all i want to save template to file on disk. I'm using > newfile = open("template.html",w") > newfile.write(str(template)) > newfile.close() > But data encodings are saved wrong, and I try diffrent programs to convert > but all i get was only mess. So is this any way to save data with encodings > cp1250 properly? > Any help will be very appreciated > Gregor I had to do it recently, reading from mysql and pushing data into a browser by cherryPy. I used : try: val= dbString.decode('utf8').encode('iso-8859-1') except UnicodeDecodeError: val= dbString The 'try:' was needed because of some extra-character on top of the 7 bits limit raising an exception. I have no more explanations about that, and I must say it was a pain in the neck to find a solution. I guess in your case, you have to replace iso-8859-1 by something else in the case it's not strictly the same that cp1250. The '4.9.2 Standard Encodings' documentation section give some explanations. Regards, jm From nick at craig-wood.com Fri Mar 3 05:30:04 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 03 Mar 2006 04:30:04 -0600 Subject: do design patterns still apply with Python? References: <8SINf.1718$No6.40137@news.tufts.edu> <1141333305.284973.54620@z34g2000cwc.googlegroups.com> <1141340833.768460.193010@j33g2000cwa.googlegroups.com> Message-ID: ajones wrote: > I would suggest getting a good grasp on OOP before you get into design > patterns. When most people start with any new concept they tend to try > and see everything in terms of their new toy, so sticking to one or two > new concepts at a time will make things a little easier. Having read the design patterns book a long time after learning OOP, I came at it with a different perspective. I found it was useful for naming techniques which I'd been using all along. A good programmer will find it easy to re-invent nearly all the patterns, but having a name for them is important. As programmers we name everything and as a corollary if it hasn't got a name it is difficult to talk about, so from that angle the book is good and very applicable to python. That said I found wading though pages of language-specific waffle extremely dull! > Design patterns are kind of like sarcasm: hard to use well, not always > appropriate, and disgustingly bad when applied to problems they are not > meant to solve. You will do just fine without them until OOP is at > least familiar to you, and by that time you should be a little better > able to use them appropriately. ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From lycka at carmen.se Wed Mar 1 07:41:05 2006 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 01 Mar 2006 13:41:05 +0100 Subject: Problem solved: Re: time.sleep(1) sometimes runs for 200 seconds under windows In-Reply-To: References: Message-ID: Paul Probert wrote: > Thanks everyone for your help. > It was the "Abouttime.exe" program, a time synch utility. To get the > problem, you have to run it as a service, and possibly it has to have > trouble connecting to its time servers. It would cause time.sleep(1) to > sometimes block for 200 seconds. Not "about" 200 seconds but always > within 199 to 202 seconds. Very strange, but it is good to have the > problem gone. So did you understand what happened? Was the system call time.time() just hanging while abouttime.exe was synching time? From gry at ll.mit.edu Mon Mar 6 22:25:05 2006 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 6 Mar 2006 19:25:05 -0800 Subject: style question: how to delete all elements in a list Message-ID: <1141701905.693384.3610@z34g2000cwc.googlegroups.com> Just curious about people's sense of style: To delete all the elements of a list, should one do: lst[:] = [] or del(lst[:]) I seem to see the first form much more often in code, but the second one seems more clearly *deleting* elements, and less dangerously mistaken for the completely different: lst = [] What do you think? -- George Young From adam.deprince at gmail.com Sun Mar 26 11:48:59 2006 From: adam.deprince at gmail.com (Adam DePrince) Date: Sun, 26 Mar 2006 11:48:59 -0500 Subject: wired md5 hashing problem In-Reply-To: <1143384987.7943.8.camel@uranos.pentacon.gov> References: <1143384987.7943.8.camel@uranos.pentacon.gov> Message-ID: <1143391739.3426.64.camel@localhost.localdomain> What do you get when you type md5sum backup.tar.bz2? - Adam On Sun, 2006-03-26 at 16:56 +0200, Matthias G?ntert wrote: > Hello list-members > > i am in the process of writing a python script to backup my data. Now I > would like to implement md5/sha1 hashes. > > # do md5 fingerprinting > if config.get("global", "crc") == "md5": > m = md5.new() > # open the file > f = open(fname, "rb") > while 1: > block = f.read(1024*1024) > if not block: > break > # generate the hash > m.update(block) > f.close() > > # write the results properly formated to a file > fd = file(fname + ".md5", "w") > fd.write(m.hexdigest()) > fd.write(" " + fname + "\n") > fd.close() > > > mguentert at uranos > md5sum -c backup.tar.bz2.md5 > /fileservice/temp/backup.tar.bz2: FAILED > md5sum: WARNING: 1 of 1 computed checksum did NOT match > > mguentert at uranos > cat backup.tar.bz2.md5 > d41d8cd98f00b204e9800998ecf8427e /fileservice/temp/backup.tar.bz2 > > so the format should be okay, but whats wrong with my piece of code?! > > Greetings > > -- > http://mail.python.org/mailman/listinfo/python-list From felipe.lessa at gmail.com Tue Mar 28 12:16:40 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 28 Mar 2006 14:16:40 -0300 Subject: in-place string reversal In-Reply-To: References: <1143554931.104392.187480@i39g2000cwa.googlegroups.com> Message-ID: <1143566200.11752.25.camel@kenshin> Em Ter, 2006-03-28 ?s 17:32 +0100, Sion Arrowsmith escreveu: > ride. And at some point reversed() will become a win: > > $ python2.4 -mtimeit 'reversed(range(200))' > 100000 loops, best of 3: 6.65 usec per loop > $ python2.4 -mtimeit 'range(200)[::-1]' > 100000 loops, best of 3: 6.88 usec per loop Not fair: $ python2.4 Python 2.4.2 (#2, Nov 20 2005, 17:04:48) [GCC 4.0.3 20051111 (prerelease) (Debian 4.0.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> range(200)[::-1] [199, 198, ..., 1, 0] >>> reversed(range(200)) >>> list(reversed(range(200))) [199, 198, ..., 1, 0] >>> list(reversed(range(200))) == range(200)[::-1] True >>>^D Now we're in a fair competition: $ python2.4 -mtimeit -s 'a=range(200)' 'a[::-1]' 100000 loops, best of 3: 2.23 usec per loop $ python2.4 -mtimeit -s 'a=range(200)' 'list(reversed(a))' 100000 loops, best of 3: 5.62 usec per loop $ calc 5.62/2.23 ~2.52017937219730941704 $ python2.4 -mtimeit -s 'a=range(200000)' 'a[::-1]' 100 loops, best of 3: 10.7 msec per loop $ python2.4 -mtimeit -s 'a=range(200000)' 'list(reversed(a))' 100 loops, best of 3: 11.5 msec per loop $ calc 11.5/10.7 ~1.07476635514018691589 But: $ python2.4 -mtimeit 'range(199, -1, -1)' 100000 loops, best of 3: 4.8 usec per loop $ python2.4 -mtimeit 'range(200)[::-1]' 100000 loops, best of 3: 7.05 usec per loop $ calc 7.05/4.8 1.46875 $ python2.4 -mtimeit 'range(199999, -1, -1)' 100 loops, best of 3: 13.7 msec per loop $ python2.4 -mtimeit 'range(200000)[::-1]' 10 loops, best of 3: 24 msec per loop $ calc 24/13.7 ~1.75182481751824817518 And worse: $ python2.4 -mtimeit 'list(reversed(range(200)))' 100000 loops, best of 3: 10.5 usec per loop $ calc 10.5/4.8 2.1875 $ python2.4 -mtimeit 'list(reversed(range(200000)))' 10 loops, best of 3: 24.5 msec per loop $ calc 24.5/13.7 ~1.78832116788321167883 HTH, -- Felipe. From jjcassidy at gmail.com Sun Mar 12 15:34:52 2006 From: jjcassidy at gmail.com (jjcassidy at gmail.com) Date: 12 Mar 2006 12:34:52 -0800 Subject: Cheese Shop: some history for the new-comers In-Reply-To: <44126523$0$1016$afc38c87@news.optusnet.com.au> References: <44126523$0$1016$afc38c87@news.optusnet.com.au> Message-ID: <1142195692.744899.129390@j52g2000cwj.googlegroups.com> richard wrote: [snip] Should the "Python Cheeseshop" have anything in it, though? Having a stocked cheese shop in relation to Python is just silly! From caleb.hattingh at gmail.com Fri Mar 31 00:56:09 2006 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 30 Mar 2006 21:56:09 -0800 Subject: Simple py script to calc folder sizes In-Reply-To: <1143764330.069364.147600@e56g2000cwe.googlegroups.com> References: <1142983179.378155.92340@v46g2000cwv.googlegroups.com> <1143700292.340111.128340@i40g2000cwc.googlegroups.com> <1143764330.069364.147600@e56g2000cwe.googlegroups.com> Message-ID: <1143784569.802579.132680@t31g2000cwb.googlegroups.com> Ben, Thank you. Caleb From steve at REMOVETHIScyber.com.au Fri Mar 3 20:50:22 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 04 Mar 2006 12:50:22 +1100 Subject: object's list index References: <1141388967.849854.239830@z34g2000cwc.googlegroups.com> <1141390100.640515.180680@u72g2000cwu.googlegroups.com> Message-ID: On Fri, 03 Mar 2006 04:48:20 -0800, Iain King wrote: > I think python only stores lists one way - i.e. each index maps to it's > value, but no backwards trace is kept from value to index. Python lists are arrays of pointers to objects. The objects themselves have no clue what lists they belong to, or what position they are in. -- Steven. From ms at cerenity.org Thu Mar 9 10:11:09 2006 From: ms at cerenity.org (Michael) Date: Thu, 09 Mar 2006 15:11:09 +0000 Subject: Simple questions on use of objects (probably faq) References: Message-ID: <4410451a$0$70318$ed2619ec@ptn-nntp-reader03.plus.net> Brian Elmegaard wrote: ... > The code that runs: > > class Foo: > def __init__(self,x): > self.x=x > > y=[] > y.append(Foo(10.0)) > y.append(Foo(110.0)) > y.append(Foo(60.0)) > > ys=[] > y_max=0.0 > y_min=0.0 > > for s in y: > ys.extend([s.x]) > y_max=max(s.x,y_max) > y_min=min(s.x,y_min) > > yz=[] > for i in range(len(ys)-1): > yz.append(ys[i+1]-ys[i]) > > What I hoped I could do: ... > yz=[y[:-1].x-y[1:].x] Based on the code that runs, you want* this: [(y[x+1].x-y[x].x) for x in range(len(y)-1) ] FWIW, "-" does not work across lists. You could use map if you wanted, but personally I prefer the explicit loop which you wanted to not use: > yz=[] > for i in range(len(ys)-1): > yz.append(ys[i+1]-ys[i]) Since personally I find that a lot clearer than: map(float.__sub__, [X.x for X in y[1:]], [X.x for X in y[:-1] ]) Regards, Michael. From waldemar.osuch at gmail.com Wed Mar 8 13:20:19 2006 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: 8 Mar 2006 10:20:19 -0800 Subject: How To Request Delivery Receipts On Emails In-Reply-To: References: Message-ID: <1141842019.421896.112970@p10g2000cwp.googlegroups.com> Gregory Pi?ero wrote: > Does anyone know how to program a Python script to send out emails > with a request delivery receipt? Is it something I can build into the > email message via the mime stuff? You have to add 'Disposition-Notification-To' header >>> from email.MIMEText import MIMEText >>> msg = MIMEText('Very important email I need confirmation on') >>> me = 'returnto at example.com' >>> msg['From'] = me >>> msg['To'] = 'workbee at example.com' >>> msg['Subject'] = 'You better follow up' >>> msg['Disposition-Notification-To'] = me print msg.as_string() Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: returnto at example.com To: workbee at example.com Subject: You better follow up Disposition-Notification-To: returnto at example.com Very important email I need confirmation on From martin at v.loewis.de Thu Mar 9 08:58:41 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 09 Mar 2006 14:58:41 +0100 Subject: encoding problem In-Reply-To: References: <440827D6.3060501@sitasoftware.lu> Message-ID: <44103491$0$7592$9b622d9e@news.freenet.de> Yves Glodt wrote: > It seems in general I have trouble with special characters... > What is the python way to deal with ??? ??? etc... > > print '?' fails here, > print u'?' as well :-( > > How am I supposed to print non-ascii characters the correct way? The second form should be used, but not in interactive mode. In a Python script, make sure you properly declare the encoding of your script, e.g. # -*- coding: iso-8859-1 -*- print u'?' That should work. If not, give us your Python version, operating system name, and mode of operation. Regards, Martin From reply.in.the.newsgroup at my.address.is.invalid Fri Mar 3 18:10:17 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 04 Mar 2006 00:10:17 +0100 Subject: How to except the unexpected? Message-ID: One of the things I dislike about Java is the need to declare exceptions as part of an interface or class definition. But perhaps Java got this right... I've writen an application that uses urllib2, urlparse, robotparser and some other modules in the battery pack. One day my app failed with an urllib2.HTTPError. So I catch that. But then I get a urllib2.URLError, so I catch that too. The next day, it encounters a urllib2.HTTPError, then a IOError, a socket.timeout, httplib.InvalidURL,... How do you program robustly with these modules throwing all those different (and sometimes undocumented) exceptions at you? A catchall seems like a bad idea, since it also catches AttributeErrors and other bugs in the program. -- Ren? Pijlman From duncan.booth at invalid.invalid Sun Mar 19 10:32:59 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Mar 2006 15:32:59 GMT Subject: C-API: A beginner's problem References: Message-ID: Heikki Salo wrote: > > And closer look tells that the code should not even compile. Is the > code cut & pasted directly? Line "list[i] = item;" tries to assign a > pointer to an int-array, which should not compile. There are other > similar oddities. ... such as the declaration of list at a point in the code which is not permitted in C, and using a non constant value for the length (which is also not allowed). From steven.bethard at gmail.com Wed Mar 1 18:10:14 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 01 Mar 2006 16:10:14 -0700 Subject: Proper class initialization In-Reply-To: References: Message-ID: Christoph Zwerschke wrote: > But I wonder whether it is possible to put all this init code into one > class initialization method, something like that: > > class A: > > @classmethod > def init_class(self): > sum = 0 > for i in range(10): > sum += i > self.sum = sum > > init_class() I don't run into this often, but when I do, I usually go Jack Diederich's route:: class A(object): class __metaclass__(type): def __init__(cls, name, bases, classdict): cls.sum = sum(xrange(10)) But you can also go something more akin to your route:: class A(object): def _get_sum(): return sum(xrange(10)) sum = _get_sum() Note that you don't need to declare _get_sum() as a classmethod, because it's not actually a classmethod -- it's getting used before the class yet exists. Just write it as a normal function and use it as such -- that is, no ``self`` or ``cls`` parameter. STeVe From tjreedy at udel.edu Tue Mar 14 22:35:20 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 14 Mar 2006 22:35:20 -0500 Subject: Printable string for 'self' References: Message-ID: "Don Taylor" wrote in message news:dv7sjt$7rb$1 at sea.gmane.org... > Is there a way to discover the original string form of the instance that > is represented by self in a method? > For example, if I have: > fred = C() > fred.meth(27) > then I would like meth to be able to print something like: > about to call meth(fred, 27) or > about to call fred.meth(27) > instead of: > about to call meth(<__main__.C instance at 0x00A9D238>, 27) That last *is* the default 'original string form of the instance'. Consider >>> [C() for i in [1,2,3]] [<__main__.C object at 0x00B536F0>, <__main__.C object at 0x00B53D90>, <__main__.C object at 0x00B53830>] If you want your instances to have a name attribute, as with functions, classes, and modules, then give them one and supply it to the init method. Note that it does not have to be a bindable name, just a string. IE, 'a[1]' could be the string identifier. Terry Jan Reedy From dan_2718 at yahoo.co.uk Sat Mar 18 08:15:35 2006 From: dan_2718 at yahoo.co.uk (dan) Date: 18 Mar 2006 05:15:35 -0800 Subject: Is there no end to Python? References: <1142622194.560240.4330@j52g2000cwj.googlegroups.com> <1142627765.683262.27120@i39g2000cwa.googlegroups.com> <1142677667.002061.269760@p10g2000cwp.googlegroups.com> Message-ID: <1142687735.653173.32680@v46g2000cwv.googlegroups.com> Steve wrote: """No need for flames. I'll content myself with pointing out that most 1.5.2 programs will run unchanged in 2.5, so the backwards compatibility picture is very good. Nobody makes you use the new features!"" Nobody makes you use new features, true...unless you are relying on a library or module that uses them...;-) cheers, Dan From johnjsal at NOSPAMgmail.com Thu Mar 30 10:22:58 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 30 Mar 2006 15:22:58 GMT Subject: RELEASED Python 2.4.3, final. In-Reply-To: References: Message-ID: Anthony Baxter wrote: > On behalf of the Python development team and the Python community, > I'm happy to announce the release of Python 2.4.3 (final). Thanks! > Assuming no major bugs pop up, the next release of Python will > be Python 2.5 (alpha 1), with a final 2.4.4 release of Python > shortly after the final version of Python 2.5. Why would 2.4.4 come out after the final release of 2.5? From workbee at gmail.com Tue Mar 21 00:55:21 2006 From: workbee at gmail.com (Enigma Curry) Date: 20 Mar 2006 21:55:21 -0800 Subject: Spidering Hacks for Python, not Perl In-Reply-To: <1142900182.388650.179350@i40g2000cwc.googlegroups.com> References: <1142900182.388650.179350@i40g2000cwc.googlegroups.com> Message-ID: <1142920521.265398.199110@e56g2000cwe.googlegroups.com> I've been looking for similar stuff recently. I haven't found much, but this is the list of links I've come across so far: Harvest Man - http://harvestman.freezope.org/ Mechanize - http://wwwsearch.sourceforge.net/mechanize/ Beautiful Soup - http://www.crummy.com/software/BeautifulSoup/ (Neither Beautiful Soup, nor Mechanize are complete crawlers but probably have a lot of the nuts and bolts) If anyone is aware of a book or other documentation like the OP would like, I would be pleased to see it as well. From paul at boddie.org.uk Thu Mar 30 05:47:01 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 30 Mar 2006 02:47:01 -0800 Subject: LDTP 0.4.0 released !!! References: <442B163B0200004400005175@mcclure.wal.novell.com> Message-ID: <1143715621.527601.178270@j33g2000cwa.googlegroups.com> Ben Finney wrote: > "A Nagappan" writes: > > > Welcome to the seventh issue of LDTP Newsletter! > > Nowhere in this newsletter do I see anything germane to a forum about > Python. Why post it here, rather than somewhere more related to Linux > or Desktops or Testing? > > And no, "because many Python programmers may be interested" is not > good enough. Is the response "because LDTP seems to use Python extensively" good enough? At least according to the Web site: http://ldtp.freedesktop.org/wiki/About http://ldtp.freedesktop.org/wiki/Docs I suppose such information could have been communicated more clearly in the newsletter, but then I suppose a bit more awareness of the different projects Python actually gets used for (ie. outside the bubble where obsessing about one's favourite "full stack" Web framework and other programming languages seems to be the fashion) wouldn't be a bad thing, either. Paul From i.failed.turing.test at gmail.com Sat Mar 4 23:01:36 2006 From: i.failed.turing.test at gmail.com (David Treadwell) Date: Sat, 4 Mar 2006 23:01:36 -0500 Subject: The old round off problem? In-Reply-To: <1141522026.813636.33310@i40g2000cwc.googlegroups.com> References: <1141498826.719803.114490@u72g2000cwu.googlegroups.com> <7xslpxki8p.fsf@ruckus.brouhaha.com> <1141522026.813636.33310@i40g2000cwc.googlegroups.com> Message-ID: I wish I knew! So I asked Google. Here's what I learned: Most implementations are based on, or similar to the implementation in the fdlibm package. sinh(x) and cosh(x) are both based on exp(x). See http:// www.netlib.org/cgi-bin/netlibfiles.pl?filename=/fdlibm/e_sinh.c exp(x) is implemented by: 1. reducing x into the range |r| <= 0.5 * ln(2), such that x = k * ln(2) + r 2. approximating exp(r) with a fifth-order polynomial, 3. re-scaling by multiplying by 2^k: exp(x) = 2^k * exp(r) sinh(x) is mathematically ( exp(x) - exp(-x) )/2 but it's not calculated directly that way. My brain hurts at this point; it's late. I'll have another go at hunting down the errors tomorrow. In the interim, does anybody out there already know the answer? :--David On Mar 4, 2006, at 8:27 PM, sam wrote: > David I beg I beg > Can you answer the question? > > Also thanks for the information on using the Taylor series. > > Sam Schulenburg > > -- > http://mail.python.org/mailman/listinfo/python-list From timr at probo.com Fri Mar 3 02:07:43 2006 From: timr at probo.com (Tim Roberts) Date: Fri, 03 Mar 2006 07:07:43 GMT Subject: newbie question References: <1141242700.105093.317210@t39g2000cwt.googlegroups.com> <1141246046.591750.315550@i39g2000cwa.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: >On 1 Mar 2006 12:47:26 -0800, "D" declaimed the >following in comp.lang.python: > >> Yep, that should work. Just keep in mind that if python.exe is not in >> your path, you will need to either specify the entire path to it >> (i.e. 'C:\python24\python C:\path\to\script\myscript.py'), or cd into >> its directory first (i.e. if you want to just run 'python >> C:\path\to\script\myscript.py'). >> > Actually, on XP at least, some combination of commands enables >things such that one can run without the "python" or the ".py" (but I >think it garbages I/O redirection and maybe command line arguments -- >though this one worked) That's the PATHEXT environment variable. C:\tmp>set PATHEXT PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.PY;.PYW;.tcl If you give a lone file name without an extension, it will try all of those extensions, in that order, to find an executable. Just add .PY to the end. There is a bug in NT's CMD.EXE that screws up redirection of stdin, but command line arguments and stdout work just fine. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jlowery at blarg.net Fri Mar 24 03:41:13 2006 From: jlowery at blarg.net (jlowery at blarg.net) Date: 24 Mar 2006 00:41:13 -0800 Subject: Question about raw string and regex In-Reply-To: <4423821a$1@news.eftel.com> References: <1143162709.817584.192910@g10g2000cwb.googlegroups.com> <1143164205.830604.151750@u72g2000cwu.googlegroups.com> <44235521@news.eftel.com> <1143172647.803951.127690@e56g2000cwe.googlegroups.com> <4423821a$1@news.eftel.com> Message-ID: <1143189673.108486.162230@z34g2000cwc.googlegroups.com> > classfix.py is not an *example* script. It is (was!) a *tool* script. I see. 2.4.2 includes a tool for modifying 0.9.8 python classes to 1.1 somthing format using a now-defunct regex module. Oh, okay. Very useful, I can see why it would still be included as part of the distribution. I was using 'regex' as the general term for regular expressions, not the module. I hadn't realized the (old, decrepit) script was using something other than 're' (r standing for 'regular', and e for 'expressions' [I'm guessing]). Pylint (with everything switched on) doesn't flag anything as deprecated, or at least I didn't notice that it did. Maybe it was because the method for deprecation hadn't been devised yet? -- I don't know, as I'm not a Python archivist. I don't think I missed line 3, but just interpeted it to apply to the purpose of the script, not the script itself. And, BTW, people will look at the source that's distributed with Python for purposes of writing their own code, be it in tools, libs, or whatever. They (should) serve as examples of current practice, IM(H)O. Old cruft should go in a source archive to dwell in the shadows forevermore. From webraviteja at gmail.com Mon Mar 6 23:16:33 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 6 Mar 2006 20:16:33 -0800 Subject: need a start point for wsdl In-Reply-To: <1141703014.199482.33860@i39g2000cwa.googlegroups.com> References: <1141703014.199482.33860@i39g2000cwa.googlegroups.com> Message-ID: <1141704123.319310.120530@i39g2000cwa.googlegroups.com> Everything you need. http://diveintopython.org/soap_web_services/index.html From root at randpoly.com Mon Mar 20 05:53:28 2006 From: root at randpoly.com (randpoly.com PostMaster) Date: Mon, 20 Mar 2006 16:23:28 +0530 Subject: Error sending message [1142594190671.2752.rpppl] from [randpoly.com] Message-ID: <20060321044547.18D6D2E1BEA@smtp41.smtp4u.com> [<00>] V-POP3bounce: Rcpt=[serg at bnr.co.uk];Error=[The maximum number of delivery attempts has been reached] [<01>] Error sending message [1142594190671.2752.rpppl] from [randpoly.com]. ID: Mail From: Rcpt To: Server: [209.120.245.170] [<02>] The reason of the delivery failure was: The maximum number of delivery attempts has been reached [<05>] Here is listed the initial part of the message: Received: from python.org (192.168.0.24:1727) by smtp.randpoly.com with [V-POP3Mail (Win32/Ix86) ESMTP Server] id for from ; Fri, 17 Mar 2006 16:46:30 +0530 From: python-list at python.org To: serg at bnr.co.uk Subject: hello Date: Fri, 17 Mar 2006 16:57:59 +0530 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_0003_E49AA146.8BEA4522" X-Priority: 3 X-MSMail-Priority: Normal From lopexx at autograf.pl Sun Mar 5 17:45:12 2006 From: lopexx at autograf.pl (=?UTF-8?B?TWFyY2luIE1pZWzFvHnFhHNraQ==?=) Date: Sun, 05 Mar 2006 23:45:12 +0100 Subject: Opening files without closing them In-Reply-To: References: <1141598002.402189.275520@i40g2000cwc.googlegroups.com> Message-ID: Marcin Miel?y?ski wrote: > Sandra-24 wrote: >> I was reading over some python code recently, and I saw something like >> this: >> >> contents = open(file).read() >> >> And of course you can also do: >> >> open(file, "w").write(obj) >> >> Why do they no close the files? Is this sloppy programming or is the >> file automatically closed when the reference is destroyed (after this >> line)? I usually use: >> >> try: >> f = open(file) >> contents = f.read() >> finally: >> f.close() >> > > this above is equivalent to: > > open(file){|f| > contents=f.read > } > > the logic taking care of everything is encapsulated in open. > > but can be done in less ruby way way :) > > > > lopex Oops I thought I was writing to c.l.ruby :D sorry for spam lopex From timr at probo.com Mon Mar 27 03:53:55 2006 From: timr at probo.com (Tim Roberts) Date: Mon, 27 Mar 2006 08:53:55 GMT Subject: sending emails to a list of recipients References: <1143331226.448124.107300@i40g2000cwc.googlegroups.com> Message-ID: "Gerard Flanagan" wrote: >Kun wrote: > >> i have the following code: >> >> ---------------------------------- >> import smtplib >>... >> msg['Subject'] = 'Purchase Confirmation' >> msg ['From'] = From >> msg['To'] = emails >> >> s = smtplib.SMTP('xxxx.xxx.xxx.edu') >> s.login('xxxxx','xxxx') >> s.sendmail(msg['From'], msg['To'], msg.as_string()) >> s.close() >> ---------------------------------- >> >> it works if msg['To'] = 'email at email.com' >> >> however, i'm trying to attach a list of emails named 'emails' to msg['To'] >> >> emails is in the following format: ['nxxx at gmail.com', 'nxxx at gmail.com', >> 'xxx at xxx.xxxx.edu'] >> >> anyone have an idea how i can modify this script to work with sending a >> list? note this is a snippet of a larger code, 'emails' is as a string >> defined earlier. What did you try? You should just be able to pass the list: s.sendmail( msg['From'], emails, msg.as_string() ) Or, if you must, msg['To'] = emails s.sendmail( msg['From'], msg['To'], msg.as_string() ) It needs to be a list or tuple of individual addresses, e-mail only, with no "nicknames". If you tried that, what did you see? >maybe try : msg['To'] = ', '.join( emails ) > >taken from: > > http://docs.python.org/lib/node597.html No, you misread the example. It uses that in the headers of the message. That won't work for the second parameter of SMTP.sendmail. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tkpmep at hotmail.com Wed Mar 15 12:38:22 2006 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 15 Mar 2006 09:38:22 -0800 Subject: Getting started with Scipy/NumPy Message-ID: <1142444302.364289.210130@j52g2000cwj.googlegroups.com> I installed SciPy and NumPy (0.9.5, because 0.9.6 does not work with the current version of SciPy), and had some teething troubles. I looked around for help and observed that the tutorial is dated October 2004, and is not as thorough as Python's documentation. Is there an alternative source of information that lists all the functions and their usage? I tried using scipy.info to get information on the std function in the stats libary, and ran into the following problem. >>> x = [1, 2, 3, 4] >>> import scipy >>> scipy.std(x) 1.2909944487358056 >>> scipy.info(std) Traceback (most recent call last): File "", line 1, in -toplevel- scipy.info(std) NameError: name 'std' is not defined >>> scipy.info(stats) Traceback (most recent call last): File "", line 1, in -toplevel- scipy.info(stats) NameError: name 'stats' is not defined >>> scipy.info(stats.std) Traceback (most recent call last): File "", line 1, in -toplevel- scipy.info(stats.std) NameError: name 'stats' is not defined However, If I redo the import as follows I can get help on std: >>> from scipy import * >>> info(std) std(a, axis=0, dtype=None) None >>> Question: why did it work this time and not on my first attempt? Thanks in advance Thomas Philips From rice.jeffrey at gmail.com Thu Mar 16 23:06:00 2006 From: rice.jeffrey at gmail.com (J Rice) Date: 16 Mar 2006 20:06:00 -0800 Subject: Threads modify "global" variable -- asking for trouble? In-Reply-To: <1142567916.313302.109920@i39g2000cwa.googlegroups.com> References: <1142567916.313302.109920@i39g2000cwa.googlegroups.com> Message-ID: <1142568360.823100.3460@i40g2000cwc.googlegroups.com> My apologizes, I missed the newish FAQ entry on this. The addrbl() method looks like this: def addRBL(self, testname, result, info=""): self.testresultsRBL[testname] = result, info So according to the FAQ, D[x] = y, where D is a dictionary, is atomic and therefore thread-safe. Right? From julienfiore at gmail.com Fri Mar 17 05:08:43 2006 From: julienfiore at gmail.com (Julien Fiore) Date: 17 Mar 2006 02:08:43 -0800 Subject: Use of Python with GDAL. How to speed up ? Message-ID: <1142590123.885456.67240@e56g2000cwe.googlegroups.com> Hi, I wrote a function to compute openness (a digital elevation model attribute). The function opens the gdal-compatible input raster and reads the values in a square window around each cell. The results are stored in a "1 line buffer". At the end of the line, the buffer is written to the output raster. It runs very slowly and I suspect the raster access to be the main bottleneck. Do you have any idea to speed-up the process ? Thanks for any help. Julien Here is the code: ################################################# ## openness.py ## ## Julien Fiore, UNIGE ## ## code inspired by Matthew Perry's "slope.cpp" # import import numpy import gdal from gdal.gdalconst import * # for GA_ReadOnly in gdal.gdal.Open() def openness(infile, outfile, R=1): """ Calculates the openness of a gdal-supported raster DEM. Returns nothing. Parameters: infile: input file (georeferenced raster) outfile: output file (GeoTIF) R: opennness radius (in cells). Window size = (2*R + 1)**2 """ # open inGrid try: inGrid = gdal.gdal.Open(infile, GA_ReadOnly ) except IOError: print 'could not open inGrid' inGridBand = inGrid.GetRasterBand(1) # get raster band # get inGrid parameters geoTrans = inGrid.GetGeoTransform() # returns list (xOrigin,xcellsize,...) cellSizeX = geoTrans[1] cellSizeY = geoTrans[5] nXSize = inGrid.RasterXSize nYSize = inGrid.RasterYSize nullValue = inGridBand.GetNoDataValue() # Create openness output file format = "GTiff" driver = gdal.gdal.GetDriverByName( format ) outGrid=driver.CreateCopy(outfile,inGrid) # Creates output raster with # same properties as input outGridBand = outGrid.GetRasterBand(1) # Access Band 1 outGridBand.SetNoDataValue(nullValue) # moving window winSize= 2*R + 1 # openness buffer array (1 line) buff = inGridBand.ReadAsArray(xoff=0, yoff=0, win_xsize=nXSize, win_ysize=1) # create distance array for Openness dist=numpy.zeros((winSize,winSize),float) for i in range(winSize): for j in range(winSize): dist[i][j]=numpy.sqrt((cellSizeX*(i-R))**2 + (cellSizeY*(j-R))**2) # openness loop for i in range(nYSize): for j in range(nXSize): containsNull = 0 # excludes the edges if (i <= (R-1) or j <= (R-1) or i >= (nYSize-R) or j >= (nXSize-R) ): buff[0][j] = nullValue continue # continues with loop next iteration # read window win = inGridBand.ReadAsArray(j-R, i-R, winSize, winSize) # Check if window has null value for value in numpy.ravel(win): if value == nullValue : containsNull = 1 break # breaks out of the smallest enclosing loop if (containsNull == 1): # write Null value to buffer buff[0][j] = nullValue continue # continues with loop next iteration else: # openness calculation with "tan=opp/adj" # East E=180.0 # 180 = max angle possible between nadir and horizon for k in range(R+1,2*R): angle= 90.0 - numpy.arctan((win[k][R]-win[R][R])/dist[k][R]) if angle References: <1143447549.045826.291850@i40g2000cwc.googlegroups.com> Message-ID: <8c7f10c60603270823t306257ebj3a5b5096ea9a75f0@mail.gmail.com> On 27 Mar 2006 00:19:09 -0800, Axel Bock wrote: > I am fooling around with the Python-COM bridge, and I have a little > question with that. > > In the component I am using is a method which will return an "Entry" > object - basically. In truth it returns some object which inherits from > entry, and I know which one, but - as said - the method will only > return the IEntry interface pointer. Now I would like to cast that one > to the one I need :) . Is there an easy way to do it, or do I have to > use the QueryInterface-method to get what I want? There's an easy way - use win32com.client.CastTo(). See the convert_tracks.py script on this page - for an example. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From rice.jeffrey at gmail.com Sat Mar 18 15:56:54 2006 From: rice.jeffrey at gmail.com (J Rice) Date: 18 Mar 2006 12:56:54 -0800 Subject: Threads modify "global" variable -- asking for trouble? In-Reply-To: References: <1142567916.313302.109920@i39g2000cwa.googlegroups.com> <1142568360.823100.3460@i40g2000cwc.googlegroups.com> Message-ID: <1142715414.421695.12790@g10g2000cwb.googlegroups.com> Thank you. Implementing a results queue was much simpler than I expected, and I think as I add this into the rest of the program it will avoid a lot of potential problems later too. From keith.b.perry at gmail.com Fri Mar 31 09:46:35 2006 From: keith.b.perry at gmail.com (kbperry) Date: 31 Mar 2006 06:46:35 -0800 Subject: Best IDE for Python? In-Reply-To: <1143813623.203852.184000@g10g2000cwb.googlegroups.com> References: <1143783179.361616.76750@i39g2000cwa.googlegroups.com> <1143813623.203852.184000@g10g2000cwb.googlegroups.com> Message-ID: <1143816395.190171.298530@t31g2000cwb.googlegroups.com> I have recently been trying out NewEdit, and it is a pretty good "IDE" for Python. The reason that I have it in quotes is because I haven't really found a true IDE (like the way Eclipse behaves for Java) for python. (I realize that Eclipse has a plug-in for Python, too). From johnjsal at NOSPAMgmail.com Sat Mar 25 15:07:45 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 25 Mar 2006 15:07:45 -0500 Subject: a problem to solve In-Reply-To: <1143274919.602219.109830@e56g2000cwe.googlegroups.com> References: <5oiUf.1818$No6.41433@news.tufts.edu> <1143237220.103038.52200@t31g2000cwb.googlegroups.com> <1143274919.602219.109830@e56g2000cwe.googlegroups.com> Message-ID: <_oedne8wPJ_CPrjZnZ2dnUVZ_tWdnZ2d@rcn.net> mensanator at aol.com wrote: > Well, I don't get the prize for most elegant. > > But that's partly because I included the ooloop6 > function. :: snip a bunch of scary code :: :) Wow, that's impressive. My solution looks a whole lot simpler than yours, but I certainly could not have done it without all your great help (the hex list, the formula, even the basic explanation of what needs to happen, i.e. Y needs to be 11111111111111111111). Thanks for taking the time to work with me on this. I don't know if I would have ever finished it without your help -- and this thing has been haunting me for months. :) From enleverlesX.XmcX at XmclaveauX.com Wed Mar 15 07:35:59 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Wed, 15 Mar 2006 13:35:59 +0100 Subject: MS word document generator References: <1142413907.226088.190740@j33g2000cwa.googlegroups.com> Message-ID: <441873b0$0$1337$8fcfb975@news.wanadoo.fr> Hi! PyRTF is old, but run OK. I use it, with some little modifs, for another usage. It was good to remember it. MCI From cito at online.de Tue Mar 21 16:26:57 2006 From: cito at online.de (Christoph Zwerschke) Date: Tue, 21 Mar 2006 22:26:57 +0100 Subject: doctest, unittest, or if __name__='__main__' In-Reply-To: <1142974528.143287.326360@e56g2000cwe.googlegroups.com> References: <1142974528.143287.326360@e56g2000cwe.googlegroups.com> Message-ID: john_sips_tea at yahoo.com wrote: > If unittest is the standard way to write test code, why do we still > have doctest? (I notice there's no mention in PEP 3000 of deprecating > the doctest module). Because both have their pros and cons and their right to exist. Doctest is really easy to use and you can kill two birds with one stone. Rather than removing one of the two, I would like to see yet another alternatise such as py.test in the standard lib, because unittest is indeed standard, but clumsy and un-pythonic. -- Christoph From steve at holdenweb.com Sun Mar 5 21:08:29 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 06 Mar 2006 02:08:29 +0000 Subject: Python advocacy in scientific computation In-Reply-To: <1141589892.094037.18410@i40g2000cwc.googlegroups.com> References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> <1141583453.403143.189400@i40g2000cwc.googlegroups.com> <1141589892.094037.18410@i40g2000cwc.googlegroups.com> Message-ID: <440B999D.2040201@holdenweb.com> sturlamolden wrote: > Robert Kern wrote: > > >>And you need to ask why Python is a better Matlab than Matlab? > > > > First there are a few things I don't like: > > 1. Intendation as a part of the syntax, really annoying. > Troll. You think this is going away because *you* don't like it? Am I to presume that you don't bother to indent your C code according to its nested block structure? If you *do* indent your C code, perhaps you can explain the additional benefits of the braces? > 2. The "self.something" syntax is really tedious (look to ruby)! > This is done because of a preference from explicit references over implied ones. It does avoid a lot of namespace confusion. By the way, anyone who can't count shouldn't be criticising programming languages. What happened to "3"? > 4. Multithreading and parallel execution is impossible AFAIK because of > the so-called GIL (global interpreter lock). Matlab is perhaps even > worse in this respect. > Right. So kindly tell us how to write thread-safe code without using a GIL. This is not an easy problem, and you shouldn't assume that all you have to do to get rid of the GIL is to wave your magic wand. There are deep reasons why the GIL is there. > 5. I don't like numpy's array slicing. Array operations should be a > part of the language, as in Matlab, Fortran 90, Ada 95, D, Octave. > Slicing *is* a part of the language, inserted into the grammar (as far as I know) precisely to support the numeric/scientific community. > > And there is a couple of questions I need answered: > > 1. Can python do "pass by reference"? Are datastructures represented by > references as in Java (I don't know yet). > All assignments store references. > 2. How good is matplotlib/pylab? I tried to install it but only get > error messages so I haven't tested it. But plotting capabilities is > really major issue. > Good enough to keep you away, apparently ;-) (Sorry, I don't use these features). > 3. Speed. I haven't seen any performance benchmarks that actually deals > with things that are important for scientific programs. > The major fact here is that no matter how fast a language is there is always a need for more speed in certain areas. Suffice it to say that Python is being used for a wide range of scientific and engineering problems to the evident satisfaction of its users. > 4. Are there "easy to use" libraries containing other stuff important > for scientific programs, e.q. linear algebra (LU, SVD, Cholesky), > Fourier transforms, etc. E.g. in Matlab I can just type, > > [u,s,v] = svd(x) % which calls LAPACK linked to ATLAS or > vendor-optimized BLAS > > Even though the language itself is very limited this type of library > functionality more than makes up for it. > The more people who join in and write libraries to add to the growing corpus of scientific and engineering libraries the sooner the answer to this question will be "we have everything you want". For the moment, however, since apparently Google isn't available where you are, a quick search for "Python LAPACK" gave http://mdp-toolkit.sourceforge.net/faq.html as its first hit. This appears to include information about how to have LAPACK make use of ATLAS' faster LAPACK routines. Satisfied? > > I have looked for alternatives to Matlab for quite a while, mainly due > to the cost, the ?poor speed and poor memory management. I am not sure > it is Python but so far I have not found anything mor promising either. > You know, recently the Python community has acquired a reputation in certain quarters for defensive support of the status quo. With ill-informed criticism like this from self-confessed beginners it's not hard to see how this myth has arisen. I'd be very surprised if Python doesn't already give you 95% of what you appear to want. If you prejudices about indented code and self-relative references blind you to the clear advantages of the Python environment then frankly you are a lost cause, and good riddance. If, on the other hand, you are prepared to engage the community and do a little bit of learning rather than just trolling, you may find that one of the most valuable features of Python is its supportive user base, whom at the moment you seem to be doing your best to offend. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From fredrik at pythonware.com Thu Mar 9 11:27:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 9 Mar 2006 17:27:44 +0100 Subject: Is the standard output thread-safe? References: Message-ID: Fernando Rodr?guez wrote: > Is the standard output thread-safe? Can I use print from several threads > without having to use a mutex? if you use sys.stdout.write on the standard sys.stdout stream, each write operation is "atomic" (thanks to the GIL). if you use other approaches (including print statements, or sys.stdout re- direction via python code), data from different streams may appear out of order. python won't crash, though. From seywaresolutions at gmail.com Tue Mar 28 09:38:26 2006 From: seywaresolutions at gmail.com (Chris S) Date: 28 Mar 2006 06:38:26 -0800 Subject: Quick Question regarding Frames In-Reply-To: <1143555706.435922.309210@g10g2000cwb.googlegroups.com> References: <1143555706.435922.309210@g10g2000cwb.googlegroups.com> Message-ID: <1143556706.259360.66610@g10g2000cwb.googlegroups.com> A little further clarification. FrameA and FrameB are in different modules. Thanks. Chris From onurb at xiludom.gro Fri Mar 31 03:18:00 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 31 Mar 2006 10:18:00 +0200 Subject: Best IDE for Python? In-Reply-To: References: <1143783179.361616.76750@i39g2000cwa.googlegroups.com> Message-ID: <442ce5fa$0$6691$626a54ce@news.free.fr> Fredrik Lundh wrote: > Dennis Lee Bieber wrote: > > >>> I want to know which is the best IDE for python.Please if >>>possible mention the features of the IDE. >> >>The best IDE is the one that YOU can be most productive in. What /I/ >>find useful may not be of interest to /you/. > > > nonsense. emacs is the best tool for everyone! Nonsense ! *Ed* is the the standard editor ! http://www.gnu.org/fun/jokes/ed.msg.html -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From wkehowski at cox.net Sat Mar 18 03:58:32 2006 From: wkehowski at cox.net (wkehowski at cox.net) Date: 18 Mar 2006 00:58:32 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: <1142646962.657648.308550@g10g2000cwb.googlegroups.com> References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1142529826.007508.286420@i39g2000cwa.googlegroups.com> <1142646962.657648.308550@g10g2000cwb.googlegroups.com> Message-ID: <1142672312.674255.165940@i39g2000cwa.googlegroups.com> Yes, the program is quite a jumble: but it works. And I didn't post to python newsgroup since I was limited to just 5 newsgroups and didn't feel like doing multiple postings to multiple newsgroups. From jstroud at ucla.edu Mon Mar 6 20:58:23 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 06 Mar 2006 17:58:23 -0800 Subject: Help - just a few lines of code needed In-Reply-To: <1141694360.291846.153820@v46g2000cwv.googlegroups.com> References: <1141694360.291846.153820@v46g2000cwv.googlegroups.com> Message-ID: lory88 at gmail.com wrote: > Unfortunately I am not able to program it myself, so You should learn how. Its very easy and will make your life better. Go to www.python.org. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From pydecker at gmail.com Thu Mar 16 17:13:03 2006 From: pydecker at gmail.com (Peter Decker) Date: Thu, 16 Mar 2006 17:13:03 -0500 Subject: Cheese Shop: some history for the new-comers In-Reply-To: <20060316061735.1fcf4919@samwise.anansi> References: <44126523$0$1016$afc38c87@news.optusnet.com.au> <4414234F.7020605@pollenation.net> <44142CAA.9080407@pollenation.net> <20060316061735.1fcf4919@samwise.anansi> Message-ID: On 3/16/06, Terry Hancock wrote: > But the usual distinction (on any project web page) is > "User" versus "Developer". > > Who is a "user" of Python? That would be you, right? It > would be fairly silly to have a page only for people who > have programs written in Python that they use (they're > *your program*'s users, not *python*'s users). > > "Developer", in context, is clearly "one who *develops* > python", not "one who *uses* python to develop programs". > > I don't see the ambiguity. I would be confused by the > opposite usage. After your long explanation, your POV makes some sense. However, no one should be expected to read such an involved explanation before understanding common terms. I am a developer. Yes, I 'use' Python for my development work, but that doesn't make me any less of a developer. A link for 'developers' would make me think that it is something I should be interested in, even if your long explanation was included next to the link (I wouldn't be likely to read it - I *know* what a developer is). -- # p.d. From jcoleman at franciscan.edu Thu Mar 2 15:32:14 2006 From: jcoleman at franciscan.edu (John Coleman) Date: 2 Mar 2006 12:32:14 -0800 Subject: Does '#hash' mean anything in IDLE? Message-ID: <1141331534.634181.275880@p10g2000cwp.googlegroups.com> Greetings, I am currently trying to learn Python through the excellent "Learning Python" book. I wrote my first non-trivial program, which began with several comment lines. One of the comment lines began with '#hash'. IDLE doesn't colorize it as a comment line but instead colors the word 'hash' in purple as if it were a key word. Wierd. The behavior seems easy to trigger: Just open up a new window in IDLE and enter these two lines: #This is a test #hash should still be a comment line Then, after saving, the second line is not colored as a comment line though the first is. Is this a bug, or do comment lines which begin with #hash have some special meaning? My program ran fine, so it seems that the interpreter itself is ignoring the line. -John Coleman From g.horvath at gmx.at Thu Mar 30 23:51:26 2006 From: g.horvath at gmx.at (Gregor Horvath) Date: Fri, 31 Mar 2006 06:51:26 +0200 Subject: How to determine COM objects/functions In-Reply-To: References: Message-ID: Servus, Scott Brown schrieb: > Say I'm operating with win32com.client and I am polling a certain > application...Internet Explorer perhaps. Is there a way to find out all > available objects and associated functions? Using dir() on the COM In PythonWin under Tools Menu there is a COM Browser. Or if you have MS-Office installed, there is a COM Browser in the VBA IDE. -- Mit freundlichen Gr??en, Ing. Gregor Horvath, Industrieberatung & Softwareentwicklung http://www.gregor-horvath.com From jess.austin at gmail.com Tue Mar 7 13:35:16 2006 From: jess.austin at gmail.com (jess.austin at gmail.com) Date: 7 Mar 2006 10:35:16 -0800 Subject: generators shared among threads References: <1141497912.606351.232440@j33g2000cwa.googlegroups.com> <1hbo9a3.1pfr3uy160d79iN%aleaxit@yahoo.com> <1141716622.587523.265790@u72g2000cwu.googlegroups.com> <1hbtiy5.jioq271n8hk43N%aleaxit@yahoo.com> Message-ID: <1141756516.058750.24240@p10g2000cwp.googlegroups.com> Alex wrote: > Last, I'm not sure I'd think of this as a reentrantQueue, so > much as a ReentrantCounter;-). Of course! It must have been late when I named this class... I think I'll go change the name in my code right now. From onurb at xiludom.gro Wed Mar 1 10:02:18 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 01 Mar 2006 16:02:18 +0100 Subject: Writing an applilcation that can easily adapt to any language In-Reply-To: References: Message-ID: <4405b7a2$0$26300$626a54ce@news.free.fr> Chance Ginger wrote: > I am rather new at Python so I want to get it right. What I am doing > is writing a rather large application with plenty of places that > strings will be used. Most of the strings involve statements of > one kind or another. > I would like to make it easy for the support people to port the > application from one language to another, German, Spanish, etc. > Rather than make them search all over for the strings to replace > is there a library that I can use to make this all easier? I > keep thinking of resources in Java, as an example. Is there > anything like it in Python? http://www.python.org/doc/2.4.2/lib/module-gettext.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 webraviteja at gmail.com Mon Mar 13 01:51:23 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 12 Mar 2006 22:51:23 -0800 Subject: Please, I Have A Question before I get started In-Reply-To: References: <40l912h0aubfgai2en7n465ml9olg746h9@4ax.com> <1hc3qpk.3dr2df1ywhnhnN%aleaxit@yahoo.com> <1142223546.729924.323410@v46g2000cwv.googlegroups.com> Message-ID: <1142232683.680734.163550@z34g2000cwc.googlegroups.com> Sigh. I could not have imagined that a link without an offending word could be taken as an insult. Perhaps the lack on accompanying text contributed? Anyway, it just was not my day (and not just you). To me, that article makes many points. I was thinking in terms of technology stagnation and particularly, essential complexity that the author stresses. That things don't keep getting much better after a point. I do not think that technology has gone backwards. Hyper card alternatives still exist. http://www.metacard.com/ They just aren't as popular anymore or obvious choices. Back then, there weren't that many alternatives. I could either program a GUI in C or to use Hypercard. The difference was stark, the choices were obvious and the market was focussed. From ben at wintersun.org Fri Mar 3 19:11:36 2006 From: ben at wintersun.org (Ben Caradoc-Davies) Date: Sat, 04 Mar 2006 08:11:36 +0800 Subject: How to except the unexpected? In-Reply-To: References: Message-ID: <4408db38$0$21898$5a62ac22@per-qv1-newsreader-01.iinet.net.au> James Stroud wrote: > except URLError, HTTPException: Aieee! This catches only URLError and binds the name HTTPException to the detail of that error. You must write except (URLError, HTTPException): to catch both. -- Ben Caradoc-Davies http://wintersun.org/ "Those who deny freedom to others deserve it not for themselves." - Abraham Lincoln From me at privacy.net Mon Mar 27 21:05:54 2006 From: me at privacy.net (Dan Sommers) Date: Mon, 27 Mar 2006 21:05:54 -0500 Subject: Difference between 'is' and '==' References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <4427d287$0$38669$edfadb0f@dread12.news.tele.dk> Message-ID: On Mon, 27 Mar 2006 11:08:36 -0300, Felipe Almeida Lessa wrote: > Em Seg, 2006-03-27 ?s 08:23 -0500, Dan Sommers escreveu: >> On Mon, 27 Mar 2006 14:52:46 +0200, >> Joel Hedlund wrote: >> >> > ... According to PEP8 (python programming style guidelines) you should >> > use 'is' when comparing to singletons like None. I take this to also >> > include constants and such ... >> >> This does *not* also mean constants and such: >> >> Python 2.4.2 (#1, Feb 22 2006, 08:02:53) >> [GCC 4.0.1 (Apple Computer, Inc. build 5247)] on darwin >> Type "help", "copyright", "credits" or "license" for more information. >> >>> a = 123456789 >> >>> a == 123456789 >> True >> >>> a is 123456789 >> False >> >>> > Not those kind of constants, but this one: > Python 2.4.2 (#2, Nov 20 2005, 17:04:48) > [GCC 4.0.3 20051111 (prerelease) (Debian 4.0.2-4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> CONST = 123456789 >>>> a = CONST >>>> a == CONST > True >>>> a is CONST > True >>>> That's a little misleading, and goes back to the questions of "what is assignment in Python?" and "What does it mean for an object to be mutable?" The line "a = CONST" simply gives CONST a new name. After that, "a is CONST" will be True no matter what CONST was. Under some circumstances, I can even change CONST, and "a is CONST" will *still* be True. >>> CONST = range(22) >>> a = CONST >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21] >>> a is CONST True >>> CONST[12] = 'foo' >>> a is CONST True >>> Right off the top of my head, I can't think of a way to make "a = b; a is b" return False. Regards, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From joel.hedlund at gmail.com Wed Mar 29 07:44:57 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Wed, 29 Mar 2006 14:44:57 +0200 Subject: Difference between 'is' and '==' In-Reply-To: References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <4427d287$0$38669$edfadb0f@dread12.news.tele.dk> <1143587890.555474.163570@e56g2000cwe.googlegroups.com> Message-ID: > [*] I discovered a neat feature I didn't know my editor had: grepping for > "<[c:python-keyword>is" Neat indeed. Which editor is that? Thanks for a quick and comprehensive answer, btw. Cheers! /Joel From plahey at alumni.caltech.edu Sun Mar 5 03:49:25 2006 From: plahey at alumni.caltech.edu (plahey at alumni.caltech.edu) Date: 5 Mar 2006 00:49:25 -0800 Subject: raw strings and \ Message-ID: <1141548565.145199.145910@e56g2000cwe.googlegroups.com> I thought I understood raw strings, then I got bitten by this: x=r'c:\blah\' which is illegal! I thought that \ had no special meanning in a raw string so why can't it be the last character? making me do: x=r'c:\blah' '\\' is just silly... From http Fri Mar 31 19:29:00 2006 From: http (Paul Rubin) Date: 31 Mar 2006 16:29:00 -0800 Subject: any() and all() on empty list? References: <7x3bh1x0ym.fsf@ruckus.brouhaha.com> <42qWf.18211$uX5.7574@tornado.texas.rr.com> <7xzmj9u1di.fsf@ruckus.brouhaha.com> <85tWf.2748$Aa1.1605@dukeread05> <7xy7ytmtk2.fsf@ruckus.brouhaha.com> Message-ID: <7xpsk2f8ab.fsf@ruckus.brouhaha.com> Ron Adam writes: > The 'not not S' is just a conversion to bool. Is the following less > contorted to you? > > >>> bool([]) > False Oh ok. Yes, bool(S) is much less contorted than "not not S". > 'Is all True' isn't the same as 'Has all True'. As I said, I'm not > questioning the mathematical meaning of the set relation 'is all > True', but wondering weather or not an alternate relation 'has all > True' would be better for use as a flow control test. > > Do you have some examples uses since it's obvious to you? # go out drinking when I'm finished with today's work if all (task.done() for task in self.things_to_do_today()): self.go_out_drinking() If I didn't have anything to do today, that should result in going out drinking immediately. > I just have a feeling we will see a lot of "S and all(S)" expressions > being used. Maybe that's not so bad, but I would prefer to not have > to do that if it turns out to the standard idiom for all testing > within a loop. I think "S and all(S)" is the right way to express that, if that's what's intended. From tobfon at gmail.com Wed Mar 1 04:43:12 2006 From: tobfon at gmail.com (=?iso-8859-1?q?Tobias_Forsl=F6w?=) Date: 1 Mar 2006 01:43:12 -0800 Subject: C++ OpenGL rendering, wxPython GUI? In-Reply-To: <1141118055.471718.90980@z34g2000cwc.googlegroups.com> References: <1141118055.471718.90980@z34g2000cwc.googlegroups.com> Message-ID: <1141206192.652227.62390@v46g2000cwv.googlegroups.com> Thanks for all the quick help! After reading your posts about how the canvases actually work it was fairly easy to make my C++ code work within a wxPython frame. Now I only have to decide If I'm actually going to use wxPython or if there is a better alternative but there seem to be plenty of threads on that subject already. From martin at v.loewis.de Mon Mar 20 16:42:47 2006 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Mon, 20 Mar 2006 22:42:47 +0100 Subject: why isn't Unicode the default encoding? In-Reply-To: References: Message-ID: <441F21D7.6000005@v.loewis.de> > I figured this might have something to do with it, but then again I > thought that Unicode was created as a subset of ASCII and Latin-1 so > that they would be compatible...but I guess it's never that easy. :) The real problem is that the Python string type is used to represent two very different concepts: bytes, and characters. You can't just drop the current Python string type, and use the Unicode type instead - then you would have no good way to represent sequences of bytes anymore. Byte sequences occur more often than you might think: a ZIP file, a MS Word file, a PDF file, and even an HTTP conversation are represented through byte sequences. So for a byte sequence, internal representation is important; for a character string, it is not. Now, for historical reasons, the Python string literals create byte strings, not character strings. Since we cannot know whether a certain string literal is meant to denote bytes or characters, we can't just change the interpretation. Unicode is a superset of ASCII and Latin-1, but not of byte sequences. Regards, Martin From bencvt at gmail.com Thu Mar 2 17:15:17 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 2 Mar 2006 14:15:17 -0800 Subject: string stripping issues In-Reply-To: <1141336803.146252.61370@e56g2000cwe.googlegroups.com> References: <1141335954.481084.277030@p10g2000cwp.googlegroups.com> <1141336803.146252.61370@e56g2000cwe.googlegroups.com> Message-ID: <1141337717.458419.296960@j33g2000cwa.googlegroups.com> Ben Cartwright wrote: > orangeDinosaur wrote: > > I am encountering a behavior I can think of reason for. Sometimes, > > when I use the .strip module for strings, it takes away more than what > > I've specified. For example: > > > > >>> a = ' Hughes. John\r\n' > > > > >>> a.strip(' ') > > > > returns: > > > > 'ughes. John\r\n' > > > > However, if I take another string, for example: > > > > >>> b = ' Kim, Dong-Hyun\r\n' > > > > >>> b.strip(' ') > > > > returns: > > > > 'Kim, Dong-Hyun\r\n' > > > > I don't understand why in one case it eats up the 'H' but in the next > > case it leaves the 'K' alone. > > > That method... I do not think it means what you think it means. The > argument to str.strip is a *set* of characters, e.g.: > > >>> foo = 'abababaXabbaXabababbbb' > >>> foo.strip('ab') > 'XabbaX' > >>> foo.strip('aabababaab') # no difference! > 'XabbaX' > > For more info, see the string method docs: > http://docs.python.org/lib/string-methods.html > To do what you're trying to do, try this: > > >>> prefix = 'hello ' > >>> bar = 'hello world!' > >>> if bar.startswith(prefix): bar = bar[:len(prefix)] > ... > >>> bar > 'world!' Apologies, that should be: >>> prefix = 'hello ' >>> bar = 'hello world!' >>> if bar.startswith(prefix): bar = bar[len(prefix):] ... >>> bar 'world!' --Ben From roy at panix.com Tue Mar 7 19:23:13 2006 From: roy at panix.com (Roy Smith) Date: Tue, 07 Mar 2006 19:23:13 -0500 Subject: Type Hinting vs Type Checking and Preconditions References: <1141764243.936880.324240@i39g2000cwa.googlegroups.com> Message-ID: In article <1141764243.936880.324240 at i39g2000cwa.googlegroups.com>, "Tom Bradford" wrote: > Here is what I mean. The following function, though conventionally > indicating that it will perform a multiplication, will yield standard > Python behaviors if a string value is passed to it: > > def multiplyByTwo(value): > return value * 2 > > Passing 14 to it will return 28, whereas passing "14" to it will return > "1414". Granted, we know and accept that this is Python's behavior > when you multiply two values, but because we don't (and shouldn't have > to) know the inner workings of a function, we don't know that the types > of the values that we pass into it may adversly affect that results > that it yields. The question is, what is the function *supposed to do*? Without knowing what it is *supposed to do*, it is impossible to say for sure whether returning "1414" is correct or not. Consider two different functions: def multiplyByTwo_v1(value): """Returns the argument multiplied by 2. If the argument is a string representation of an integer, another string is returned which is the string representation of that integer multiplied by 2. """" return value * 2 def multiplyByTwo_v2(value): """Returns the argument multiplied by 2. """" return value * 2 The first one should return "28" when passed "14". If it returns "1414", it's broken. I know this seems rather silly and pedantic, but it's an important point. I was once working on a project which historically didn't have any unit tests. We had a function called something like "isValidIP" in the library which returned True or False depending on whether its (string) argument was a valid IP address. I wrote some unit tests and it failed on a corner case like "255.255.255.255" (or maybe it was "0.0.0.0"). Turns out, the original author was using it in some special situation where 255.255.255.255 wasn't valid for his purposes. We got down to, "OK, *you* document what the function is supposed to do, and *I'll* write a unit test which proves it does what the documentation says". You would think that would be easy, but it never got done because we couldn't get everybody to agree on what the function was supposed to do. It was being used in production code. I would have thought it would bother people that we were using a function without knowing what it was supposed to do, but what really bothered people more was that we had a unit test that was failing. And the solution was to back out unit test. Sometimes politics trumps technology. PS, as far as I know, that project is now dead, but for other reasons far worse than one underspecified function :-) From kent at kentsjohnson.com Wed Mar 8 06:15:00 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 08 Mar 2006 06:15:00 -0500 Subject: cgi problem In-Reply-To: <7xk6b5mjpw.fsf_-_@ruckus.brouhaha.com> References: <7xk6b5mjpw.fsf_-_@ruckus.brouhaha.com> Message-ID: <440eb7e9$1_3@newspeer2.tds.net> Paul Rubin wrote: > I'm trying to write a simple cgi that reads a post from the user's > browser, does some stuff with the form data, and redirects the browser > back to the originating url, i.e. I want the cgi to send a 302 > redirect. > > There's no obvious way in the cgi module to set the response code to > anything but 200. I.e. the run_cgi method automatically sends the 200 > response without giving any way to suppress it (like nph-whatever in > Apache). Is that a missing feature that I should add, or am I trying > to do something dumb? Set the Location: header to the new URL. http://hoohoo.ncsa.uiuc.edu/cgi/out.html http://www.algonet.se/~ug/html+pycgi/redirect.html Kent From elpX at adsihqX.com Thu Mar 9 18:57:50 2006 From: elpX at adsihqX.com (Dr. Pastor) Date: Thu, 09 Mar 2006 23:57:50 GMT Subject: About IDLE? In-Reply-To: References: Message-ID: <2i3Qf.3304$Bj7.629@newsread2.news.pas.earthlink.net> Any reply? Dr. Pastor wrote: > Installed Python 2.4.2 on Windows XP. > Activated IDLE. > Loaded the following into the Edit window: > --- > # dates are easily constructed and formatted (Tutorial 10.8) > > from datetime import date > now = date.today() > now > > now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") > > # dates support calendar arithmetic > > birthday = date(1985, 12, 1) > age = now - birthday > age.days > --- > When I select Run Module in the Edit window, I got only > two >>> after the RESTART line. > I expected to see the output of several commands! > Typing in age.days do produce the number of days. > > Why I do not get any output? > Thanks for any guidance. > > From johnjsal at NOSPAMgmail.com Wed Mar 8 10:31:06 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Mar 2006 15:31:06 GMT Subject: why no block comments in Python? Message-ID: <_MCPf.1749$No6.40293@news.tufts.edu> I'm still tyring to figure out what "Pythonic" means, and I have a feeling the answer to my question may fall into that category. Are block comments somehow unpythonic? From mensanator at aol.com Fri Mar 24 20:56:17 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 24 Mar 2006 17:56:17 -0800 Subject: a problem to solve References: <5oiUf.1818$No6.41433@news.tufts.edu> <1143237220.103038.52200@t31g2000cwb.googlegroups.com> Message-ID: <1143251777.489064.28690@u72g2000cwu.googlegroups.com> John Salerno wrote: > mensanator at aol.com wrote: > > > a = [0xf5fdc,0xf6edb,0xbddb7,0x6fddd,0xeb7ed,0xb977f,0xbfed3,0xedef5] > > b = [0xddb7d,0xfaddb,0xde75f,0xeef7a,0xdd77b,0xdfbce,0xb77dd,0x7ef5d] > > c = [0xf37bd,0xdfaee,0xddd6f,0xddfb6,0xb9efb,0xb7bbe,0xecfbd,0xb75df] > > d = [0x77edb,0xbb7ee,0xdf773,0x7bdeb,0x7ddaf,0xdeeeb,0xfb35f,0xbb7dd] > > > Once you see that a[0],b[0],c[0],d[0] is not a solution, try a > > different set of switches. Repeat until you find a set that works. > > There is, in fact a solution, but I won't reveal it unless you ask. > > Using your hex list, I combined the four correct switches with the & > operator, and the result was 0. Shouldn't it be 1 for the correct answer? No. First of all, combining them with the & operator would be the asnswer to having all four lamps lit in the same position. But you want exactly 3 (in any combination). The correct way to combine the switches (using my answer of a[7] b[2] c[5] d[3]) is to use the boolean expression I gave you initially: >>> y = ((c[5] & d[3]) & (a[7] ^ b[2])) | ((a[7] & b[2]) & (c[5] ^ d[3])) >>> y 1048575 Note the answer is 2**20-1, not 1, the correct answer will have a 1 in EACH of the 20 bit positions (when y is printed in binary). Is 1048575 the right answer? >>> import gmpy >>> print gmpy.digits(y,2) 11111111111111111111 Yes, it is the right answer. If you calculate y for EVERY possible permutation of switches a[0] b[0] c[0] d[0] a[0] b[0] c[0] d[1] a[0] b[0] c[0] d[2] a[0] b[0] c[0] d[3] a[0] b[0] c[0] d[4] a[0] b[0] c[0] d[5] a[0] b[0] c[0] d[6] a[0] b[0] c[0] d[7] a[0] b[0] c[1] d[0] . . . a[7] b[7] c[7] d[5] a[7] b[7] c[7] d[6] a[7] b[7] c[7] d[7] you'll find that a[7] b[2] c[5] d[3] is the ONLY solution. From paulgeeleher at gmail.com Sun Mar 19 08:29:47 2006 From: paulgeeleher at gmail.com (sophie_newbie) Date: 19 Mar 2006 05:29:47 -0800 Subject: Counting number of each item in a list. In-Reply-To: <7xek0ybnut.fsf@ruckus.brouhaha.com> References: <1142772092.958602.272260@e56g2000cwe.googlegroups.com> <7xek0ybnut.fsf@ruckus.brouhaha.com> Message-ID: <1142774987.654644.185910@i40g2000cwc.googlegroups.com> Hi Paul, Ur bit of code works, thanks so much, just for anyone reading this use 'h = {}' instead of h = 0. Thanks From steve at REMOVETHIScyber.com.au Fri Mar 10 20:50:09 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 11 Mar 2006 12:50:09 +1100 Subject: Why python doesn't use syntax like function(, , x) for default parameters? References: <44115054$0$14937$834e42db@reader.greatnowhere.com> Message-ID: On Fri, 10 Mar 2006 11:33:56 -0500, Terry Reedy wrote: > Actually, I consider the unique calling pattern for x/range to be something > of a wart. Learning this inconsistency was at least a minor problem. It > is a rather extreme example of typing laziness beats purity. Amazing. I consider it to be a rather extreme example of practicality beating purity, an excellent example of interface design. But I guess that's why Guido is BDFL. Well, that and the fact that he invented Python *wink* -- Steven. From rice.jeffrey at gmail.com Wed Mar 8 12:11:11 2006 From: rice.jeffrey at gmail.com (J Rice) Date: 8 Mar 2006 09:11:11 -0800 Subject: Bidirectional communication over unix socket (named pipe) In-Reply-To: <1141836504.118212.173060@z34g2000cwc.googlegroups.com> References: <1141836504.118212.173060@z34g2000cwc.googlegroups.com> Message-ID: <1141837871.654935.214240@j52g2000cwj.googlegroups.com> OK, never fails that I find a solution once I post a problem. If I use a stream rather than a datagram, it seems to work fine. So... for my education, how would I make this work with a datagram, if I insisted on doing it that way? From mailpitches at email.com Fri Mar 17 17:47:38 2006 From: mailpitches at email.com (mailpitches at email.com) Date: 17 Mar 2006 14:47:38 -0800 Subject: Python installation problem Message-ID: <1142635658.097143.261790@j52g2000cwj.googlegroups.com> I'm using OS X 10.4.5. I have an easy problem that I can't solve: I have two versions of python installed. 2.3 came with the OS and 2.4 I installed via fink. When I call python from the command-line it calls 2.4. When I just call a *.py file like test.py, it calls 2.3. 1. How do I make both these kinds of calls work with 2.4. 2. How do I uninstall v. 2.3 completely. Tnx From nogradi at gmail.com Wed Mar 22 13:24:12 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 22 Mar 2006 19:24:12 +0100 Subject: Wrap a dictionary in a class? In-Reply-To: <1143049779.758828.189050@u72g2000cwu.googlegroups.com> References: <1143049779.758828.189050@u72g2000cwu.googlegroups.com> Message-ID: <5f56302b0603221024g6ce7614ctdc6ec76def4a7d1a@mail.gmail.com> > In another thread, it was recommended that I wrap a dictionary in a > class. > How do I do so? I guess this is what you want: http://vsbabu.org/mt/archives/2003/02/13/joy_of_python_classes_and_dictionaries.html HTH, Daniel From martin at v.loewis.de Thu Mar 23 01:44:25 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 23 Mar 2006 07:44:25 +0100 Subject: LONG_BIT PROBLEM on Sun Solaris 5.8 linking python In-Reply-To: <1143068597.976727.183480@j33g2000cwa.googlegroups.com> References: <1143068597.976727.183480@j33g2000cwa.googlegroups.com> Message-ID: <442243c9$0$28776$9b622d9e@news.freenet.de> Nancy wrote: > I know there are lots of messages about this already posted but Im > seeing this on Solaris 5.8. Sunfire > I'm using the sun compiler. All the other messages blamed it on linux > red hat gcc compilers and glib. Thanks. So what is the value of SIZEOF_LONG in pyconfig.h? When you compile the file #include LOOK HERE: LONG_BIT with cc -E -D_XOPEN_SOURCE=500 -D_XOPEN_SOURCE_EXTENDED=1 a.c what output do you get after LOOK HERE? Regards, Martin From root at randpoly.com Sun Mar 19 23:52:08 2006 From: root at randpoly.com (randpoly.com PostMaster) Date: Mon, 20 Mar 2006 10:22:08 +0530 Subject: Error sending message [1142825372138.2332.rpppl] from [randpoly.com] Message-ID: <20060320095146.43C7C2E1683@smtp41.smtp4u.com> [<00>] V-POP3bounce: Rcpt=[f-prot at f-prot.com];Error=[550 Error: Invalid Attachment] [<01>] Error sending message [1142825372138.2332.rpppl] from [randpoly.com]. ID: Mail From: Rcpt To: Server: [209.120.245.170] [<02>] The reason of the delivery failure was: 550 Error: Invalid Attachment [<05>] Here is listed the initial part of the message: Received: from python.org (192.168.0.24:1479) by smtp.randpoly.com with [V-POP3Mail (Win32/Ix86) ESMTP Server] id for from ; Mon, 20 Mar 2006 08:59:32 +0530 From: python-list at python.org To: f-prot at f-prot.com Subject: Status Date: Mon, 20 Mar 2006 09:11:17 +0530 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_0013_4CCCFBDD.E2A9B589" X-Priority: 3 X-MSMail-Priority: Normal From antroy at gmail.com Tue Mar 21 11:06:01 2006 From: antroy at gmail.com (Ant) Date: 21 Mar 2006 08:06:01 -0800 Subject: New-style Python icons In-Reply-To: <1142942389.170814.196640@z34g2000cwc.googlegroups.com> References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> <1142938350.321554.69260@t31g2000cwb.googlegroups.com> <1142942389.170814.196640@z34g2000cwc.googlegroups.com> Message-ID: <1142957161.302935.27210@i39g2000cwa.googlegroups.com> It's easier than that in this case. Just unpack the icons in yout Python directory over the top of the existing ones. The change should get picked up the next time you log on. -- Ant... From bill_maxwell_notMyRealAddress at notreal.net Sat Mar 4 12:00:00 2006 From: bill_maxwell_notMyRealAddress at notreal.net (Bill Maxwell) Date: Sat, 04 Mar 2006 12:00:00 -0500 Subject: Write a GUI for a python script? References: <1141377383.013956.44090@j33g2000cwa.googlegroups.com> Message-ID: On Fri, 3 Mar 2006 07:19:34 -0500, "Peter Decker" wrote: >I started with wxPython and struggled with it for a long time. I was >able to get the job done, but using it never seemed natural. Then I >found the Dabo project, whose ui module wraps wxPython into a much >more Pythonic, consistent interface. Since then I've been able to >create GUIs without much effort at all. I highly recommend Dabo if you >are thinking about wxPython. Dabo does look really nice, but seems like it has a ways to go yet. I downloaded it a couple of weeks ago, and the very first thing I wanted to do doesn't seem to be supported. I tried to create a simple application with a Notebook control inside a frame. The Notebook control doesn't appear to be supported yet. Is that right, or am I just not looking in the right places? Bill From deets at nospam.web.de Fri Mar 3 14:03:51 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 03 Mar 2006 20:03:51 +0100 Subject: PyQt issue In-Reply-To: <1141411143.575922.296190@p10g2000cwp.googlegroups.com> References: <1141411143.575922.296190@p10g2000cwp.googlegroups.com> Message-ID: <46ri8mFcb76tU1@uni-berlin.de> dmbkiwi at gmail.com schrieb: > I'm trying to write a simple dialog with PyQt. Ive got this code as > one of the slots: > > def setFixed(self): > if len(str(self.fixed_label.displayText())) == 0: > QMessageBox.critical(self, "Label Missing", "You must enter > a label.") > else: > print str(self.fixed_date_month.currentText()) > print str(self.fixed_date_day.currentText()) > day_text = str(self.fixed_date_day.curentText()) + ' ' + > str(self.fixed_date_month.currentText()) > self.date_list.insertItem(date_text) > > self.label_list.insertItem(str(self.fixed_label.displayText())) > > When run, the output is: > > January > 1 > Traceback (most recent call last): > File "/home/matt/karamba/date_calc/date_config.py", line 285, in > setFixed > day_text = str(self.fixed_date_day.curentText()) + ' ' + > str(self.fixed_date_month.currentText()) > AttributeError: curentText > > How can it print .currentText(), but then throw an AttributeError when > I try an put them in a variable? Because you wrote curentText - note the missing t. Which the error-message clearly says. I suggest you acquaint yourself with pylint & pychecker. Diez From felipe.lessa at gmail.com Thu Mar 16 19:29:41 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Thu, 16 Mar 2006 21:29:41 -0300 Subject: My Generator Paradox! In-Reply-To: <1142554666.740989.303350@p10g2000cwp.googlegroups.com> References: <1142554666.740989.303350@p10g2000cwp.googlegroups.com> Message-ID: <1142555381.22756.1.camel@kenshin> Em Qui, 2006-03-16 ?s 16:17 -0800, vbgunz escreveu: > print generatorFunction() # > print generatorFunction().next() # item1 > print generatorFunction().next() # item1 > print generatorFunction().next() # item1 Each time you say "generatorFunction()", it gives you a new generator, thus returning the first item again. From John-Whitlock at ieee.org Mon Mar 13 13:35:42 2006 From: John-Whitlock at ieee.org (JW) Date: 13 Mar 2006 10:35:42 -0800 Subject: Please, I Have A Question before I get started References: <40l912h0aubfgai2en7n465ml9olg746h9@4ax.com> Message-ID: <1142274942.137973.15950@i39g2000cwa.googlegroups.com> Skipper wrote: > I can not believe that there isn't a GUI programing tool that will > allow me to build GUI apps - just like I use Dreamweaver to build a > web page ... a WYSIWYG builder that does a few simplet things and > calls other programs ... > > Oh well .... no silver bullet! If you are interested in programming, the best way is to find a motivating goal to learn. It sounds like you have a very motivating goal. However, it will probably take quite a long time for you to get to a point where you can make a useful tool for your son. While your problem description is straightforward, the implementation is not. One route you might consider is contacting your local engineering college for help. My alumnus recently solicited funds for a "Life Interaction Device" for Abigail, a 6 year old girl with Cerebral Palsy: http://www.ee.utulsa.edu/Abigail/index.html It sounds as if Abagail's needs are far greater than your son's, but your project would make an interesting design project for CS students at an undergraduate level. From dongdonglove8 at hotmail.com Wed Mar 8 01:54:52 2006 From: dongdonglove8 at hotmail.com (dongdong) Date: 7 Mar 2006 22:54:52 -0800 Subject: how to download a zip or rar file to local machine using python? In-Reply-To: References: <1141795347.072982.216900@j52g2000cwj.googlegroups.com> <1141797709.923751.50230@j52g2000cwj.googlegroups.com> <1141798101.698272.61370@u72g2000cwu.googlegroups.com> Message-ID: <1141800892.116488.12300@v46g2000cwv.googlegroups.com> thanks a lot. From g.brandl-nospam at gmx.net Sat Mar 18 10:04:06 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sat, 18 Mar 2006 16:04:06 +0100 Subject: __dict__ strangeness Message-ID: <482lr6Fhs1jvU1@individual.net> Hi, can someone please tell me that this is correct and why: >>> class C(object): ... pass ... >>> c = C() >>> c.a = 1 >>> c.__dict__ {'a': 1} >>> c.__dict__ = {} >>> c.a Traceback (most recent call last): File "", line 1, in ? AttributeError: 'C' object has no attribute 'a' >>> >>> class D(object): ... __dict__ = {} ... >>> d = D() >>> d.a = 1 >>> d.__dict__ {} >>> d.__dict__ = {} >>> d.a 1 Thanks, Georg From hancock at anansispaceworks.com Tue Mar 7 18:59:56 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 7 Mar 2006 17:59:56 -0600 Subject: Any advantage in LISPs having simpler grammars than Python? In-Reply-To: <1141770067.041526.292360@p10g2000cwp.googlegroups.com> References: <1141770067.041526.292360@p10g2000cwp.googlegroups.com> Message-ID: <200603071759.56388.hancock@anansispaceworks.com> On Tuesday 07 March 2006 04:21 pm, seberino at spawar.navy.mil wrote: > Is there any advantage to a language having a nice mathematically > compact grammar like LISP does? (or at least used to?) > Many have admired the mathematically simple grammar of LISP > in which much of the language is built up from conses IIRC. > Python's grammar seems complicated by comparison. > > Is this anything to worry about? Certainly I'm not going to lose any sleep over it. ;-) I think the cool thing about Lisp's tiny grammar is that it proves you can make a grammar that small work. It's minimalist to the extreme. The trouble is, while it may be easy for the machine to parse, it isn't the machine's clerical ability we are worried about! Ultimately any such determination is aesthetic, so there will inevitably be disagreement, but for some of us, at least, the Python syntax is a much better balance between simplicity and adequate discrimination and visual cues. Perl, for example, is much further along on that spectrum -- it has a large number of "punctuation" symbols (symbolic operators, really). Lots of "visual cues", but it's not simple at all. The nice thing about symbolic operators is that they are very compact and very easy to distinguish from one another. The bad thing about them is that they are not as easy to remember as words, and they are very difficult to look up, compared to words. Therefore, you have to "just know" what they mean. Or rather -- learning them is part of comprehending the core language, as opposed to something you learn as you go along. Word symbols, like Python's keywords, standard library functions, classes, and methods are easier to look up in the manual if you get stuck. They also put user constructs on a much more even footing with things built into the language. So -- I don't have to write a PEP if I just want a useful feature I can implement in a module. Using that approach, I can construct a "domain specific language" in python or lisp. In a way, that's what all modules do (at least they allow you to expand the vocabulary of the language, though most leave the grammar alone). Lisp gives you that kind of power to the nines. It lets you rewrite the vocabulary, grammar, and whatever to get the job done the way you want. And then people use it. And that leaves you, as the end user, to learn a new language for each application. And the extremely limited grammar means that there are few visual cues to sort out what is part of Lisp, what is part of a library, and what is your own code. It's like a paper without hierarchical heading styles. You can read it, but it's not as easy as one which is structured with visual cues as to what is a heading, what is a section number, what is emphasized, etc. Some people apparently love Lisp, but I really could never get over the nested parentheses making my eyes cross. ;-) I think experienced Lisp programmers must learn to visually parse the *words* in the Lisp program to determine the structure, but I find that really unhelpful, myself. Remember that you *can* represent your program with nothing but two characters, "0" and "1" -- even simpler than Lisp. That doesn't mean that that's the "preferred form for editing" it. ;-) Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From cm012b5105 at blueyonder.co.uk Thu Mar 23 11:26:28 2006 From: cm012b5105 at blueyonder.co.uk (cm012b5105) Date: Thu, 23 Mar 2006 16:26:28 -0000 Subject: raw_input Message-ID: <00cb01c64e96$89ba0b90$0801a8c0@nigel> Hi there i am hoping some one could help me out with a small problem i am in the process of learning python. I am trying to write an interactive programme, This is a short example. if s = raw_input ("hello what's your name? ") if s=='carmel ': print "Ahh the boss's wife" What i would like to know is what if she doesn't write carmel she rights say carm short of me writing if s=='carm': on a new line is there a shorter way of doing this so i can cover all angles on how she might write her name. Thanks nigeps I appologise for my earlier thread -------------- next part -------------- An HTML attachment was scrubbed... URL: From msuemnig at jjhill.org Thu Mar 30 10:18:38 2006 From: msuemnig at jjhill.org (msuemnig at jjhill.org) Date: 30 Mar 2006 07:18:38 -0800 Subject: Apache and Python and Ubuntu In-Reply-To: <1143716269.799330.49080@v46g2000cwv.googlegroups.com> References: <1143672083.347654.81330@v46g2000cwv.googlegroups.com> <87k6ac7tgl.fsf@ieee.org> <1143675274.665079.244110@i40g2000cwc.googlegroups.com> <1143716269.799330.49080@v46g2000cwv.googlegroups.com> Message-ID: <1143731918.768602.117470@g10g2000cwb.googlegroups.com> Paul, thank you so much for your information and help! That was exactly the issue. I added ExecCGI and addHandler cgi-script .cgi to the sites-available/default file and bounce the service and it's working! Thanx again! From steven.bethard at gmail.com Tue Mar 21 16:25:05 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 21 Mar 2006 14:25:05 -0700 Subject: Why "class exceptions" are not deprecated? In-Reply-To: <1142964085.356976.166620@t31g2000cwb.googlegroups.com> References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com> Message-ID: Gregory Petrosyan wrote: > 1) From 2.4.2 documentation: > There are two new valid (semantic) forms for the raise statement: > raise Class, instance > raise instance Check `PEP 8`_ -- the latter form is preferred: """ When raising an exception, use "raise ValueError('message')" instead of the older form "raise ValueError, 'message'". """ .. _PEP 8: http://www.python.org/dev/peps/pep-0008/ STeVe From johnjsal at NOSPAMgmail.com Sat Mar 25 00:00:25 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 25 Mar 2006 00:00:25 -0500 Subject: a problem to solve In-Reply-To: <1143251777.489064.28690@u72g2000cwu.googlegroups.com> References: <5oiUf.1818$No6.41433@news.tufts.edu> <1143237220.103038.52200@t31g2000cwb.googlegroups.com> <1143251777.489064.28690@u72g2000cwu.googlegroups.com> Message-ID: mensanator at aol.com wrote: > No. First of all, combining them with the & operator would be > the asnswer to having all four lamps lit in the same position. > But you want exactly 3 (in any combination). The correct way > to combine the switches (using my answer of a[7] b[2] c[5] d[3]) > is to use the boolean expression I gave you initially: Ah, that makes sense. I think I have a handle on it now. Of course, you did the grunt work of making the hex list, which might not have been so fun, but now I can work on using it to get the solution. Once I do, I'd love to compare my answer to yours, because something tells me yours will be much more elegant. :) From felipe.lessa at gmail.com Thu Mar 30 02:03:44 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Thu, 30 Mar 2006 04:03:44 -0300 Subject: python challenge question (string manipulation) In-Reply-To: <1143699625.052366.276950@i39g2000cwa.googlegroups.com> References: <1143699625.052366.276950@i39g2000cwa.googlegroups.com> Message-ID: <1143702224.30858.28.camel@kenshin> Em Qua, 2006-03-29 ?s 22:20 -0800, Caleb Hattingh escreveu: > That is very succint. Rewriting my shift function given earlier: > > >>> import string > >>> alpha = string.ascii_lowercase > >>> print alpha > abcdefghijklmnopqrstuvwxyz > >>> def shift(lst, n): > return [lst[(i+len(lst)-n)%len(lst)] for i,item in enumerate(lst)] It sure is short, but is it fast? Compare to the function below (the fastest I can think of ATM): def shift(lst, n): first = (-n) % len(lst) result = list(lst[first:]) # if lst is a iterable but not a list result.extend(lst[:first]) return result Now benchmarking: $ python2.4 -mtimeit -s "def shift(lst, n): return [lst[(i+len(lst)-n)% len(lst)] for i,item in enumerate(lst)]" "shift('abcdefghijklmnopqrstuvwxyz',2)" 10000 loops, best of 3: 21.5 usec per loop $ python2.4 -mtimeit -s "def shift(lst, n): length = len(lst); first = (-n) % length; result = list(lst[first:]); result.extend(lst[:first]); return result" "shift('abcdefghijklmnopqrstuvwxyz',2)" 100000 loops, best of 3: 3.98 usec per loop The five-line version is more than five times faster than the two-line counterpart. But it scales better too: $ python2.4 -mtimeit -s "string = 'abcdefghijklmnopqrstuvwxyz'*10000 def shift(lst, n): length = len(lst); first = (-n) % length; result = list(lst[first:]); result.extend(lst[:first]); return result" "shift(string,2)" 100 loops, best of 3: 10.6 msec per loop $ python2.4 -mtimeit -s "string = 'abcdefghijklmnopqrstuvwxyz'*10000 def shift(lst, n): return [lst[(i+len(lst)-n)%len(lst)] for i,item in enumerate(lst)]" "shift(string,2)" 10 loops, best of 3: 206 msec per loop With a 10 000 times larger list it takes almost 20 times less time. Of course a human can't perceive a 17.52 usec difference in time, but I'd like to make it clear that the two-line function shouldn't be used on a real system. What we learn from this? When it's not needed (like now), please don't iterate over all items of a list. HTH, -- Felipe. From paddy3118 at netscape.net Tue Mar 21 02:45:12 2006 From: paddy3118 at netscape.net (Paddy) Date: 20 Mar 2006 23:45:12 -0800 Subject: Design mini-lanugage for data input In-Reply-To: References: Message-ID: <1142927112.502231.235450@t31g2000cwb.googlegroups.com> Hmm, Do you know about JSON and YAML? http://en.wikipedia.org/wiki/JSON http://en.wikipedia.org/wiki/YAML They have the advantage of being maintained by a group of people and being available for a number of languages. (as well as NOT being XML :-) - Cheers, Paddy. -- http://paddy3118.blogspot.com/ From 1024nospam at freesurf.fr Wed Mar 29 10:54:02 2006 From: 1024nospam at freesurf.fr (1024nospam at freesurf.fr) Date: 29 Mar 2006 07:54:02 -0800 Subject: New Python website, new documentation ? Message-ID: <1143647642.708869.250060@i39g2000cwa.googlegroups.com> Hi, I was wondering : as there has been a change in python.org website with a new design, is it planned for the documentation section to be revamped as well ? If yes, would it be just a appearance renewal or would there also be changes in the doc itself ? Martin. From roy at panix.com Sat Mar 18 20:14:22 2006 From: roy at panix.com (Roy Smith) Date: Sat, 18 Mar 2006 20:14:22 -0500 Subject: Where can we find top-notch python developers? References: Message-ID: In article , Nicholas Reville wrote: > Hi, I hope this is an OK spot for this question: An even better place would be to post your position on the Python Jobs Board, http://www.python.org/community/jobs/ From siasookhteh at gmail.com Thu Mar 23 21:48:51 2006 From: siasookhteh at gmail.com (siasookhteh at gmail.com) Date: 23 Mar 2006 18:48:51 -0800 Subject: Strings and % sign fails - Help Please Message-ID: <1143168531.461348.130160@t31g2000cwb.googlegroups.com> I also posted this in Django Users group, but figured it probably has more relevance for python group. It seems like a freak problem to me. I spent a long hour to track the problem down and here it is: The following statement fails because it has the '%' sign in it. cursor.execute("select '%'") The error is: IndexError: list index out of range How do I address this problem? Please note that the following work just fine: cursor.execute("select 'x'") and the following also fails with the same error: cursor.execute("""select '%'""") cursor.execute("select '\%'") astr = "select '\%'" cursor.execute(astr) I greatly appreciate all helps, Regards, Sia From lycka at carmen.se Thu Mar 9 07:58:23 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 09 Mar 2006 13:58:23 +0100 Subject: New python.org website In-Reply-To: <1141904100.412502.318910@i40g2000cwc.googlegroups.com> References: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> <1141803728.187013.195770@v46g2000cwv.googlegroups.com> <1141832835.420083.154930@u72g2000cwu.googlegroups.com> <1141904100.412502.318910@i40g2000cwc.googlegroups.com> Message-ID: Nicola Musatti wrote: > The obviously perfect logo would be Kaa's face: > http://disney.go.com/vault/archives/villains/kaa/kaa.html The Soviet version is better, and I think most of the Maugli movies are made before 1973, which means that they aren't copyrighted outside the former Soviet Union. (Disclaimer: IANAL) I'm not sure either version really works as a logo though. From petr at tpc.cz Thu Mar 9 08:07:48 2006 From: petr at tpc.cz (Petr Jakes) Date: 9 Mar 2006 05:07:48 -0800 Subject: accesibility of the namespace In-Reply-To: References: <1141897375.385047.258520@j52g2000cwj.googlegroups.com> Message-ID: <1141909668.196271.295080@j33g2000cwa.googlegroups.com> Ooooops. My keyboard (fingers) was faster than my mind :( So.... There is more than one "run-time changed variable" in the dictionary and not all strings in the dictionary are formatted using % operator. Example: lcd={ 2:{2:(("Enter you choice"),("Your kredit= %3d" % (kredit)))}, 4:{2:(("Your choice: %2s" % (keyboard)),("%-20s" % (actKeyboard)))}} I do not know which variable(s) to use for the % operator in the time of the call of the value (% formatted string) from the dictionary. This is also the reason why the variable names are stored in the dictionary with the strings. Any other suggestions? Thanks Petr Jakes From larry.bates at websafe.com Tue Mar 21 11:49:50 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 21 Mar 2006 10:49:50 -0600 Subject: How can I compare if 2 files has duplicate entries in python? In-Reply-To: <1142957182.894221.29460@i39g2000cwa.googlegroups.com> References: <1142957182.894221.29460@i39g2000cwa.googlegroups.com> Message-ID: yinglcs at gmail.com wrote: > I am new to python. How can I compare if 2 files has duplicate entries > in python? > Is there an example for that? What if the files are big and I don't > want to read the whole file in memory. > > Thank you. > You need to supply more info. If you just want to determine if two files are exactly alike you can just calculate the md5 checksum or each file. If they are different, the files are different. See: http://docs.python.org/lib/module-md5.html If you want to compare files line by line see following: http://docs.python.org/lib/module-difflib.html -Larry Bates From tom.willis at gmail.com Wed Mar 8 09:58:38 2006 From: tom.willis at gmail.com (Thomas G. Willis) Date: Wed, 8 Mar 2006 09:58:38 -0500 Subject: New python.org website In-Reply-To: <1141828189.686141.216580@v46g2000cwv.googlegroups.com> References: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> <1141757893.030386.123090@i40g2000cwc.googlegroups.com> <440ea467$0$38682$edfadb0f@dread12.news.tele.dk> <1141828189.686141.216580@v46g2000cwv.googlegroups.com> Message-ID: I don't necessarily like it, but I think the true test is whether a pointy haired manager type can be convinced that python can be taken seriously as a welcome addition to the programming arsenal. I think the site re-design will aid in that area more so than the previous one. I'm not feeling the new logo though. But it's better than what I can produce in an svg editor/ -- Thomas G. Willis ----------------------------------------------- http://i-see-sound.com http://tomwillis.sonicdiscord.com America, still more rights than North Korea -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at ucla.edu Sun Mar 5 20:37:45 2006 From: jstroud at ucla.edu (James Stroud) Date: Sun, 05 Mar 2006 17:37:45 -0800 Subject: searching for the number of occurences of a string In-Reply-To: References: Message-ID: M.N.A.Smadi wrote: > hi; > say i have a text file with a string ( say '(XYZ)') and I want to find > the number of line where this string has occured. What is the best way > to do that? > > what about if that string was say a 0 with leading and trailing white > spaces, would that be any different? > > thanks > moe smadi Some pieces: To read every line in a file: afile = open(filename) for aline in afile: do_something_here() To see if a string contains another string, try if another_string() in astring: do_something_else_here() If you need regular expressions, see the re module. For instance: import re regex = re.compile(r'(?:\s+0\s+)|\(XYZ\)') print regex.search(' 0 ').group() print regex.search(' (XYZ) abc').group() if regex.search('abcdefg'): print 'yep' else: print 'nope' That should be everything you could possibly need. Its up to you to put it all together. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From steven.bethard at gmail.com Thu Mar 2 13:14:09 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 02 Mar 2006 11:14:09 -0700 Subject: Proper class initialization In-Reply-To: <4406dbe9$1_2@newspeer2.tds.net> References: <4406dbe9$1_2@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > Steven Bethard wrote: >> I don't run into this often, but when I do, I usually go Jack >> Diederich's route:: >> >> class A(object): >> class __metaclass__(type): >> def __init__(cls, name, bases, classdict): >> cls.sum = sum(xrange(10)) > > I think you should call the superclass __init__ as well: > > class __metaclass__(type): > def __init__(cls, name, bases, classdict): > super(__metaclass__, cls).__init__(name, bases, classdict) > cls.sum = sum(xrange(10)) Yes, thanks for the catch. I'd like to use super there, but I think you'll find that it doesn't work because of the order in which A and __metaclass__ get created: >>> class A(object): ... class __metaclass__(type): ... def __init__(cls, name, bases, cdict): ... super(__metaclass__, cls).__init__(name, bases, cdict) ... cls.sum = sum(xrange(10)) ... Traceback (most recent call last): File "", line 1, in ? File "", line 4, in __init__ NameError: global name '__metaclass__' is not defined >>> class A(object): ... class __metaclass__(type): ... def __init__(cls, name, bases, classdict): ... super(A.__metaclass__, cls).__init__(name, bases, classdict) ... cls.sum = sum(xrange(10)) ... Traceback (most recent call last): File "", line 1, in ? File "", line 4, in __init__ NameError: global name 'A' is not defined I played around with a few solutions to this problem, but it seems like the cleanest one is just to avoid super: >>> class A(object): ... class __metaclass__(type): ... def __init__(cls, name, bases, cldict): ... type.__init__(cls, name, bases, cldict) ... cls.sum = sum(xrange(10)) ... Of course, this means you can't use some sorts of multiple inheritance with A.__metaclass__... STeVe P.S. Here's the best way I found that still uses super: >>> class A(object): ... class __metaclass__(type): ... def __init__(cls, name, bases, cldict): ... try: ... meta = A.__metaclass__ ... except NameError: ... meta = cldict['__metaclass__'] ... super(meta, cls).__init__(name, bases, cldict) ... cls.sum = sum(xrange(10)) ... From webraviteja at gmail.com Mon Mar 6 23:11:10 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 6 Mar 2006 20:11:10 -0800 Subject: Checking function calls In-Reply-To: References: Message-ID: <1141704670.552060.265480@e56g2000cwe.googlegroups.com> You can match if the list contains the legal number of arguments with. func_variable.func_code.co_argcount Type checking arguments has to be done manually since Python is a dynamic language. Perhaps, you could try some typechecking decorators. http://www.ilowe.net/software/typecheck/ >From the docs, this one raises TypeCheckError (not TypeError), so you should do fine. From dubrovsky at physics.uq.edu.au Thu Mar 30 21:11:15 2006 From: dubrovsky at physics.uq.edu.au (Alejandro Dubrovsky) Date: Fri, 31 Mar 2006 12:11:15 +1000 Subject: urllib2 through basic auth'ed proxy References: Message-ID: John J. Lee wrote: > FWIW, at a glance, Python 2.3.4 has neither of the bugs I mentioned, > but the code I posted seems to work with 2.3.4. I'm not particularly > interested in what's wrong with 2.3.4's version or your usage of it > (probably both), since bugfix releases for 2.3 are no longer > happening, I believe. > "ah, yes, that works" on 2.3.4. Excellent. (I don't see what's so ugly about that code, but i'm mostly accustomed to my own) Thanks, alejandro From dorward at yahoo.com Fri Mar 17 03:09:40 2006 From: dorward at yahoo.com (David Dorward) Date: Fri, 17 Mar 2006 08:09:40 +0000 Subject: python newbie, linux novice, needs to run spamassassin References: <1142564731.867968.318910@e56g2000cwe.googlegroups.com> Message-ID: Lonnie Princehouse wrote: > * at this point someone will probably chime in saying it's possible to > rig spamassassin with a bayesian filter It is on by default AFAIK. -- David Dorward Home is where the ~/.bashrc is From wkehowski at cox.net Thu Mar 23 05:32:10 2006 From: wkehowski at cox.net (wkehowski at cox.net) Date: 23 Mar 2006 02:32:10 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: <1142545215.632905.284520@j33g2000cwa.googlegroups.com> References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1142544373.164023.50140@z34g2000cwc.googlegroups.com> <1142545215.632905.284520@j33g2000cwa.googlegroups.com> Message-ID: <1143109930.768224.160910@j33g2000cwa.googlegroups.com> Hello, The solution that would have the most utility would be one where the elements are generated one-by-one, loop-like, so that they can be used in the body of a loop, and to avoid the fact that even with exclusion the cardinality of the target set EX^n could be in the millions even with a full list of wc's, that is, a list containing at least one wc of every length in 2..(n-1). I don't know enough Lisp, Haskell or Qi/Prolog to know if the solutions so far can be modified to do this. The Python program is too slow for large sets. Walter Kehowski From s99999999s2003 at yahoo.com Tue Mar 28 21:14:51 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 28 Mar 2006 18:14:51 -0800 Subject: sending ctrl C to a process Message-ID: <1143598491.283734.37180@t31g2000cwb.googlegroups.com> hi i have a program that works very similar to tail -f in Unix It will need a Ctrl-C in order to break out of the program. I wish to run this program using python (either thru os.system() or some other subprocess modules) and how can i pass Ctrl-C to this program to terminate it in python? thanks From vbgunz at gmail.com Sun Mar 5 08:57:34 2006 From: vbgunz at gmail.com (vbgunz) Date: 5 Mar 2006 05:57:34 -0800 Subject: Argument Precedence (possible bug?) In-Reply-To: References: <1141562380.331820.42260@i40g2000cwc.googlegroups.com> <1141562704.979483.63730@i40g2000cwc.googlegroups.com> Message-ID: <1141567054.504497.147310@i39g2000cwa.googlegroups.com> I am sorry I hung you up on a typo Peter Hansen. On line 5 *arg4 should have been *par4. I hope it makes complete sense now. Sorry. From michaeltaft at gmail.com Sat Mar 11 12:49:10 2006 From: michaeltaft at gmail.com (mwt) Date: 11 Mar 2006 09:49:10 -0800 Subject: Python Love :) Message-ID: <1142099350.122968.35220@i39g2000cwa.googlegroups.com> I've only been goofing around with Python for about a month now, but already I am in love. I never get that feeling -- so common with Java -- that I'm swimming upstream, struggling to force the language to do what I want. Python makes it feel effortless and easy. From uche.ogbuji at gmail.com Fri Mar 3 21:00:07 2006 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 3 Mar 2006 18:00:07 -0800 Subject: XSLT and gettext? In-Reply-To: References: Message-ID: <1141437607.043679.271510@p10g2000cwp.googlegroups.com> KW wrote: > I'm looking for a nice way to do i18n with XSLT, preferably using the > gettext framework. Currently I'm using 4Suite for XSLT processing. Do > you know of any solutions to this problem? > > If no solutions currently exist, I'll try to write something myself. Any > ideas on how to do this properly? Any existing python code to start with? > > I was thinking about wrappingg the text in a new XML tag, say and > processing this to generate an XSL for alle languages, but it will also > require printf like substitution to do this properly. 4Suite has some friendly gettext-based i18n extensions. See: http://copia.ogbuji.net/blog/2005-06-14/i18n_for_X -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ From tomerfiliba at gmail.com Sat Mar 25 15:29:07 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 25 Mar 2006 12:29:07 -0800 Subject: pondering about the essence of types in python Message-ID: <1143318547.286867.9940@u72g2000cwu.googlegroups.com> let's start with a question: ========== >>> class z(object): ... def __init__(self): ... self.blah=5 ... >>> class x(object): ... def __init__(self): ... z.__init__(self) ... >>> y=x() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in __init__ TypeError: unbound method __init__() must be called with z instance as first argument (got x instance instead) ========== and the question is -- WHY? what is a type? generally speaking, if everything were an object, the type only defines the MRO (method resolution order) for that object. x.y first looks at the instance, then the class, then the parent classes, etc. (this was changed a little in python2.3 to something more complicated, but it's basically the same). you can see the mro like this: ========== >>> class x(object): pass >>> class y(x): pass >>> class z(y): pass >>> a=z() >>> print a.__class__.mro() [, , , ] ========== after all, if we stay out of builtin types, all python objects are dicts, which support chian-lookup according to the mro. and a method is just a function that takes the instance as a first argument. so why is all this type hassle necessary? if we've taken it that far already, then let's really go over the edge. I WANT TO DERIVE FROM INSTANCES. not only types. why? i'm the developer of rpyc (http://rpyc.sf.net), and i got a request from someone to add support for deriving from remote types. the concrete example he gave was quite silly, but after i thought about it a little, i said why not try? a little intro about rpyc: it gives you proxies (instances) to remote objects, which can be instances, functions, or classes. and that user wanted to do something like this: class my_frame(conn.modules.wx.Frame): ... so the client was actually creates the graphics on the server. not very usable, but why not? all it means is, when he does "my_frame.xyz", python should add the remote type to the mro chain. not too bizar. but __mro__ is a readonly attribute, and deriving from instances is impossible (conn.modules.wx.Frame is a PROXY to the class)... and again -- WHY? these all look like INTENTIONAL limitations. someone went around and added type checks (which are NOT pythonic) into the cPython implementation. argh. why do that? so i thought -- let's be nasty. i created a function that creates a class that wraps an instance. very ugly. small children and peope with heart problems should close their eyes. ============ def derive_from(obj): class cls(object): def __getattr(self, name): return getattr(obj, name) return cls class my_frame(derive_from(conn.modules.wx.Frame)): .... ============ the actual implementation is quite more complex, but that shows the concept. so now i'm experimenting with that little shit. but then i came to the problem that methods check the type of the first argument... ARGH. dont check types. DONT. the whole point of duck-typing is you DONT CHECK THE TYPES. you just work with objects, and instead of TypeError you'd get AttribiuteError, which is much better. AAARRRRRRGGGHH. python is EVIL at the low level. the high-level is just fine, but when you try to go under the hood... you better go with an exorcist. -tomer From aleaxit at yahoo.com Mon Mar 20 10:30:55 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Mar 2006 07:30:55 -0800 Subject: Pycrypto - active ?? References: <1142804398.710230.117640@j33g2000cwa.googlegroups.com> <1142807299.141313.306980@i40g2000cwc.googlegroups.com> <1142841321.980154.320340@u72g2000cwu.googlegroups.com> <7xslpdl7yg.fsf@ruckus.brouhaha.com> <1142856119.461122.293150@i40g2000cwc.googlegroups.com> <1142861008.662593.172900@t31g2000cwb.googlegroups.com> Message-ID: <1hchm5b.1vgq264sk3olaN%aleaxit@yahoo.com> Frank Millman wrote: ... > The docs say that if you have any of m2crypto, cryptlib, pycrypto, or > GMPY installed, it will be used for fast cryptographic operations. I ... > However, I have not found an MSW binary for Python 2.4 for any of the > above packages. TLSLite works ok by itself, but it is noticeably slower > when transferring large amounts of data. There are several Windows binaries of GMPY for 2.4 on sourceforge.net, optimized for different intel and AMD processors. Since gmpy.sf.net is gmpy's home, I don't understand what you mean by "have not found". Alex From fortepianissimo at gmail.com Mon Mar 6 12:55:13 2006 From: fortepianissimo at gmail.com (fortepianissimo) Date: 6 Mar 2006 09:55:13 -0800 Subject: Package organization: where to put 'common' modules? In-Reply-To: <440b92c9$1_3@newspeer2.tds.net> References: <1141419542.750676.176150@z34g2000cwc.googlegroups.com> <44098830$1_3@newspeer2.tds.net> <1141599776.392714.28350@i39g2000cwa.googlegroups.com> <1141605355.963705.3860@z34g2000cwc.googlegroups.com> <440b92c9$1_3@newspeer2.tds.net> Message-ID: <1141667712.948490.184370@v46g2000cwv.googlegroups.com> Kent Johnson wrote: > Paul Boddie wrote: > > Yes, Python does this - it puts the directory of bar.py (B in this > > case) in sys.path, but not the directory in which you're sitting when > > you run the program from the shell (A in this case). > > This seems to be OS dependent. If I put 'print sys.path' at the start of > site.py (which does most of the setup of sys.path), one element of the > path is an empty string. This is expanded by > main() -> removeduppaths() -> makepath() -> os.path.abspath() > to the current working dir. > > This is Python 2.4.2 on Win2K. > > Kent Following your example, I tried to use symlink to solve my problem. I have the following dir structure: A |--- util | |--- foo.py | |--- B | |--- util (symlink to ../util) | |--- bar.py | |--- main.py ------ util/foo.py: print 'foo initialized' def baz(): print 'foo.baz() here' ------ B/bar.py: from util import foo foo.baz() ------ main.py: import sys from util import foo print id(sys.modules['util.foo']) from B import bar print id(sys.modules['util.foo']) ------ Now when I run python main.py in dir A, I got the following result (Python 2.4.2, Mac OS X): foo initialized 3698320 foo initialized foo.baz() here 3698320 My question is why foo got initialized twice? From fredrik at pythonware.com Wed Mar 8 10:40:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 8 Mar 2006 16:40:05 +0100 Subject: why no block comments in Python? References: <_MCPf.1749$No6.40293@news.tufts.edu> Message-ID: John Salerno wrote: > I'm still tyring to figure out what "Pythonic" means, and I have a > feeling the answer to my question may fall into that category. Are block > comments somehow unpythonic? only in the sense that python don't have them. but they're pretty pointless, if you have a modern editor. (and if you don't, you can quickly comment out regions by putting them inside a triple-quoted string.) From i.failed.turing.test at gmail.com Sun Mar 5 17:53:14 2006 From: i.failed.turing.test at gmail.com (David Treadwell) Date: Sun, 5 Mar 2006 17:53:14 -0500 Subject: The old round off problem? In-Reply-To: <1141538471.690041.151060@e56g2000cwe.googlegroups.com> References: <1141498826.719803.114490@u72g2000cwu.googlegroups.com> <7xslpxki8p.fsf@ruckus.brouhaha.com> <1141522026.813636.33310@i40g2000cwc.googlegroups.com> <1141538471.690041.151060@e56g2000cwe.googlegroups.com> Message-ID: On Mar 5, 2006, at 1:01 AM, sam wrote: > > David Treadwell wrote: >> exp(x) is implemented by: >> >> 1. reducing x into the range |r| <= 0.5 * ln(2), such that x = k * >> ln(2) + r >> 2. approximating exp(r) with a fifth-order polynomial, >> 3. re-scaling by multiplying by 2^k: exp(x) = 2^k * exp(r) >> >> sinh(x) is mathematically ( exp(x) - exp(-x) )/2 but it's not >> calculated directly that way. >> >> My brain hurts at this point; it's late. I'll have another go at >> hunting down the errors tomorrow. In the interim, does anybody out >> there already know the answer? >> >> :--David > I tried the exp(x) equivalent of sinh(x) and cosh(x) with the same > results. > I think I will write my own or steal the Taylor(f(x),x,n) function in > both C++, and python. After dreaming about this last night, there is a pretty straightforward answer. A Python or C double precision real will deliver around 16 or 17 meaningful decimal digits. from math import * for x_int in range(20): x_real = 1.0 + x_int sinh_x = sinh(x_real) cosh_x = cosh(x_real) c2s2_x = (cosh_x + sinh_x)*(cosh_x - sinh_x) print 'x:% *.2f, cosh: % .4e, sinh: % .4e, c2-s2: % .4e'% (6, x_real, cosh_x, sinh_x,c2s2_x-1.0) x: 1.00, cosh: 1.5431e+00, sinh: 1.1752e+00, c2-s2: 0.0000e+00 x: 2.00, cosh: 3.7622e+00, sinh: 3.6269e+00, c2-s2: -2.3315e-15 x: 3.00, cosh: 1.0068e+01, sinh: 1.0018e+01, c2-s2: -2.4314e-14 x: 4.00, cosh: 2.7308e+01, sinh: 2.7290e+01, c2-s2: 1.4766e-13 x: 5.00, cosh: 7.4210e+01, sinh: 7.4203e+01, c2-s2: 1.4677e-12 x: 6.00, cosh: 2.0172e+02, sinh: 2.0171e+02, c2-s2: 1.9333e-12 x: 7.00, cosh: 5.4832e+02, sinh: 5.4832e+02, c2-s2: -3.6329e-11 x: 8.00, cosh: 1.4905e+03, sinh: 1.4905e+03, c2-s2: -1.7109e-10 x: 9.00, cosh: 4.0515e+03, sinh: 4.0515e+03, c2-s2: 3.1331e-09 x: 10.00, cosh: 1.1013e+04, sinh: 1.1013e+04, c2-s2: 2.6562e-08 x: 11.00, cosh: 2.9937e+04, sinh: 2.9937e+04, c2-s2: -1.2103e-07 x: 12.00, cosh: 8.1377e+04, sinh: 8.1377e+04, c2-s2: 2.2313e-06 x: 13.00, cosh: 2.2121e+05, sinh: 2.2121e+05, c2-s2: -4.2111e-06 x: 14.00, cosh: 6.0130e+05, sinh: 6.0130e+05, c2-s2: -1.0882e-04 x: 15.00, cosh: 1.6345e+06, sinh: 1.6345e+06, c2-s2: 1.2143e-04 x: 16.00, cosh: 4.4431e+06, sinh: 4.4431e+06, c2-s2: -6.8998e-03 x: 17.00, cosh: 1.2077e+07, sinh: 1.2077e+07, c2-s2: -1.0174e-02 x: 18.00, cosh: 3.2830e+07, sinh: 3.2830e+07, c2-s2: -2.1590e-02 Consider just the characteristic, int(log10(), of cosh(x) and sinh (x). In the table, it varies from 0 to +7. Because it ends up getting squared, the characteristic of cosh(x)**2 varies from 0 to 15. If you subtract that number from 16, you get roughly the precision of the result: The precision of the final answer for cosh(x)**2 - sinh(x) **2 - 1.0 is roughly 17 - 2 * int(log10(cosh(x)). So, this isn't a rounding problem. It is a lack of precision problem. As I suspected last night, subtracting two very large and almost equal numbers from each other eliminates precision. It just doesn't look like it once the internal hex is converted to decimal. Because the problem is mathematically correct, there must be a better way to state it so that you don't end up with this problem. :--David -------------- next part -------------- An HTML attachment was scrubbed... URL: From stijndesaeger at gmail.com Wed Mar 29 04:01:00 2006 From: stijndesaeger at gmail.com (vdrab) Date: 29 Mar 2006 01:01:00 -0800 Subject: any() and all() on empty list? In-Reply-To: References: Message-ID: <1143622860.716668.231370@v46g2000cwv.googlegroups.com> > I'm completely on board with the semantics for any(). But all() bothers > me. If all() receives an empty list, it will return True, and I don't > like that. To me, all() should be a more restrictive function than any(), > and it bothers me to see a case where any() returns False but all() > returns True. Who should we call to report this fallacy? GvR? Goedel? Tarski? no, wait... Frege ! or wait... actually, I think that must be Aristotle. Sorry Aristotle, the ol' syllogisms have to go. ; -) All silliness aside, the meaning of all() in python corresponds just fine with "all" in both language and logic. s. From brochu121 at gmail.com Fri Mar 31 15:13:39 2006 From: brochu121 at gmail.com (david brochu jr) Date: Fri, 31 Mar 2006 15:13:39 -0500 Subject: String Matching Message-ID: <9583ed900603311213i67a7be95m1266094bfcc5f6de@mail.gmail.com> Hello, I am trying to write a script that takes strings from a text file and searches to see if they are present in another text file...here is the code: import os import re search = open("c:\python24\scripts\pii\expected_rules_results.txt") def find(x): file = open("c:\python24\scripts\pii\dave.txt") regexp = re.compile(x) for line in file.readlines(): if regexp.search(line): print "Found", x break file.close() for x in search: find(x) search.close() Unfortunately the strings I will be searching for contain numerous "*" that cause an error. For example, when try to search for: http://www.widget.com/personal_firewall.csp/?pin=****{6} I get the error message: Traceback (most recent call last): File "C:\Python24\scripts\PII\search find(x) File "C:\Python24\scripts\PII\search regexp = re.compile(x) File "C:\Python24\lib\sre.py", line return _compile(pattern, flags) File "C:\Python24\lib\sre.py", line raise error, v # invalid expressio sre_constants.error: multiple repeat Anyone know how to get around this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alainpoint at yahoo.fr Wed Mar 15 01:28:51 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 14 Mar 2006 22:28:51 -0800 Subject: Is this possible in Python? In-Reply-To: References: <1142238871.199749.243470@p10g2000cwp.googlegroups.com> <1142282467.270698.142780@p10g2000cwp.googlegroups.com> <1142331474.355167.20970@i40g2000cwc.googlegroups.com> <1142340220.720530.27590@p10g2000cwp.googlegroups.com> <1142360116.660443.67380@i40g2000cwc.googlegroups.com> <1142371981.816264.113390@v46g2000cwv.googlegroups.com> Message-ID: <1142404131.261774.240480@u72g2000cwu.googlegroups.com> Steven D'Aprano wrote: > > Doesn't work for me either: > > >>> def magic(arg): > ... import inspect > ... return inspect.stack()[1][4][0].split("magic")[-1][1:-1] > ... > >>> magic(3+4) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in magic > TypeError: unsubscriptable object > > > Kay gets an AssertionError, I get a TypeError. I think describing it as > "proof of concept" is rather optimistic. > > Here is the inspect.stack() I get: > > [(, '', 2, 'magic', None, None), > (, '', 1, '?', None, None)] > > > -- > Steven. You just proved what i was saying: this is no robust code. It apparently does not work from the command line. It has problems with comments on the same line. It might have problems with multi-line arguments, etc .... Please feel free to improve the above function and make it robust. (meanwhile, i removed the SOLUTION FOUND from the subject title, until you come up with such a robust version ;-)) Alain From sandro at e-den.it Sun Mar 5 06:49:53 2006 From: sandro at e-den.it (Sandro Dentella) Date: Sun, 05 Mar 2006 11:49:53 GMT Subject: lists: += vs. .append() & oddness with scope of variables Message-ID: I'd like to understand why += operator raises an error while .append() does not. My wild guess is the parses treats them differently but I cannot understand why this depends on scope of the variables (global or class variables): a = [0] class foo(object): def __init__(self): print "a: ", a # += does not work if 'a' is global #a += [1] a.append(2) print "a= ", a class bar(object): b = [0] def __init__(self): print "b: ", self.b # += *does* work if 'a' is class var self.b += [1] self.b.append(2) print "b= ", self.b if __name__ == '__main__': x = foo() y = bar() a: [0] a= [0, 2] b: [0] b= [0, 1, 2] uncommenting 'a += [1]' would raise: a: Traceback (most recent call last): File "c1.py", line 26, in ? x = foo() File "c1.py", line 7, in __init__ print "a: ", a UnboundLocalError: local variable 'a' referenced before assignment TIA sandro *:-) -- Sandro Dentella *:-) e-mail: sandro at e-den.it http://www.tksql.org TkSQL Home page - My GPL work From jeff at schwabcenter.com Fri Mar 3 15:58:52 2006 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Fri, 03 Mar 2006 20:58:52 GMT Subject: why does close() fail miserably on popen with exit code -1 ?! In-Reply-To: <4407559E.2030301@rcsreg.com> References: <1140416836.030294.289800@f14g2000cwb.googlegroups.com> <4407559E.2030301@rcsreg.com> Message-ID: Tobiah wrote: > phase:toby:~> echo 'exit -1' | bash > phase:toby:~> echo $? > 255 http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/exitcodes.html Exit Code Number: 255 [1] Meaning: Exit status out of range Example: exit -1 Comments: exit takes only integer args in the range 0 - 255 [1] Out of range exit values can result in unexpected exit codes. An exit value greater than 255 returns an exit code modulo 256. For example, exit 3809 gives an exit code of 225 (3809 % 256 = 225). From daniel.evers at rwth-aachen.de Thu Mar 30 09:23:09 2006 From: daniel.evers at rwth-aachen.de (Daniel Evers) Date: Thu, 30 Mar 2006 16:23:09 +0200 Subject: How to determine an object is "scriptable" References: <1143726903.153135.317880@j33g2000cwa.googlegroups.com> Message-ID: <4927udFmla3dU1@news.dfncis.de> Richard Brodie wrote: > subscriptable: supports an indexing operator, like a list does. Right. You can check this e.g. with hasattr(x, "__getitem__") because the __getitem__ method is used for indexing. Daniel From tuvas21 at gmail.com Tue Mar 7 21:37:00 2006 From: tuvas21 at gmail.com (Tuvas) Date: 7 Mar 2006 18:37:00 -0800 Subject: AES encryption In-Reply-To: <1141762684.628567.216910@j52g2000cwj.googlegroups.com> References: <1141742505.544888.253280@e56g2000cwe.googlegroups.com> <1141762684.628567.216910@j52g2000cwj.googlegroups.com> Message-ID: <1141785420.104468.256060@e56g2000cwe.googlegroups.com> Okay, I figured out the problem. The problem was that my algorythm filed the numbers into the matrix as so: 1 2 3 4 5 6 7 8... While it should have been 1 5 9 13 2 6 10 14 ... When this was fixed, the program works great! That's what I get for testing only asymetrical keys... Oh well, thanks for the help in fixing the problem! From grflanagan at yahoo.co.uk Wed Mar 1 10:29:15 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 1 Mar 2006 07:29:15 -0800 Subject: Accessing 'mangled' class attrbutes Message-ID: <1141226955.820389.87860@z34g2000cwc.googlegroups.com> Hello all I would like to do the following: from elementtree.SimpleXMLWriter import XMLWriter class HtmlWriter(XMLWriter, object): def write_raw(self, text): super( HtmlWriter, self ).flush() super( HtmlWriter, self ).__write(text) but because of the name-mangling caused by '__write' I get: AttributeError: 'super' object has no attribute '_HtmlWriter__write'. Is there any simple way round this situation in general? (I just want to write out a HTML 'DOCTYPE' declaration) Thanks Gerard From rphillips at engineer.co.summit.oh.us Mon Mar 13 15:06:54 2006 From: rphillips at engineer.co.summit.oh.us (paron) Date: 13 Mar 2006 12:06:54 -0800 Subject: Please, I Have A Question before I get started In-Reply-To: References: <40l912h0aubfgai2en7n465ml9olg746h9@4ax.com> Message-ID: <1142280414.775225.135700@e56g2000cwe.googlegroups.com> Well, there's OpenLaszlo, which handles the sounds/animation for http:www.pandora.com, I understand. It may be overkill for a desktop app, but it's free. It was originally written in Python, I think, but it uses ECMAScript for scripting. It's free, and reportedly handles sounds and animations, and isn't too hard to program. Ron From vbgunz at gmail.com Thu Mar 16 19:17:46 2006 From: vbgunz at gmail.com (vbgunz) Date: 16 Mar 2006 16:17:46 -0800 Subject: My Generator Paradox! Message-ID: <1142554666.740989.303350@p10g2000cwp.googlegroups.com> I am afraid that this is the first time in which I would probably need something explained to me as if I were a little child. I am having a hard time getting this through my thick skull. What in the world is wrong with this!? ''' ########################################################### ''' def generatorFunction(sequence=['item1', 'item2', 'item3']): for item in sequence: yield item yieldedValue = generatorFunction() '''this seems to work perfectly.''' print '-' * 32 print yieldedValue # print yieldedValue.next() # item1 print yieldedValue.next() # item2 print yieldedValue.next() # item3 '''this is where things don't make any sense!''' print '-' * 32 print generatorFunction() # print generatorFunction().next() # item1 print generatorFunction().next() # item1 print generatorFunction().next() # item1 ''' ########################################################### ''' the first set of calls assigned to yieldedValue work but the second set without assignment don't. I asked for help on this at #python (I love those people in there!) and was told the following... generatorFunction() is a call (obvious) when calling the second set, I am resetting the iteration and this explains why I only and always get item1. ok. *but* why in the world does the first set of calls work? technically, isn't yieldedValue == generatorFunction() on a name basis? I mean isn't the following technically the same? generatorFunction() yieldedValue = generatorFunction() aren't they both the same? To me they should be but obviously this creates the point of this paradox. I don't understand what is happening here... Can someone care to explain why the assignment works but not the direct call? In a sense shouldn't the assignment yield the same results as the direct call and vice versa? I am confused :( Thank you for any help on this! From and-google at doxdesk.com Tue Mar 21 15:29:57 2006 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 21 Mar 2006 12:29:57 -0800 Subject: New-style Python icons In-Reply-To: References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> Message-ID: <1142972997.227201.43190@u72g2000cwu.googlegroups.com> Fredrik Lundh wrote: > could you perhaps add an SVG version ? Yes. I'll look at converting when I've used them a bit and am happy with them. I think some of the higher-level Xara effects may not convert easily to SVG but I'm sure there'll be workarounds of some sort. -- And Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From reply.in.the.newsgroup at my.address.is.invalid Sat Mar 4 06:51:40 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 04 Mar 2006 12:51:40 +0100 Subject: How to except the unexpected? References: <7xek1ipzgh.fsf@ruckus.brouhaha.com> <7xy7zqmzc8.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin : >We have to get Knuth using Python. Perhaps a MIX emulator and running TeXDoctest on his books will convince him.. -- Ren? Pijlman From michaeltaft at gmail.com Tue Mar 7 00:35:13 2006 From: michaeltaft at gmail.com (mwt) Date: 6 Mar 2006 21:35:13 -0800 Subject: New python.org website In-Reply-To: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> References: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> Message-ID: <1141709713.082379.137990@j33g2000cwa.googlegroups.com> Wow. That does look fantastic. Thumbs up! From ethrandil at gmx.net Sun Mar 26 18:10:42 2006 From: ethrandil at gmx.net (Clemens Hepper) Date: Mon, 27 Mar 2006 01:10:42 +0200 Subject: Bitwise OR? In-Reply-To: References: <1143187977.384459.225840@i40g2000cwc.googlegroups.com> <1143190128.783253.62430@i40g2000cwc.googlegroups.com> Message-ID: Adam DePrince wrote: >> BTW: Is there something like a sizeof() method for int numbers? > > import struct > help( strict.calcsize ) Mh, that doesn't do what i want. I'd like to have something like: def size(number): return sizeof(number) > Why one bit at a time? Good question... Here my new approach based on your idea: _digits = { 0:"0000", 1:"1000", 2:"0100", 3:"1100", 4:"0010", 5:"1010", 6:"0110", 7:"1110", 8:"0001", 9:"1001", 0xa:"0101", 0xb:"1101", 0xc:"0011", 0xd:"1011", 0xe:"0111", 0xf:"1111"} def bitstring2(number): """lsb------>msb""" rlist = list() if number >= 0: while number: rlist.append( _digits[number & 0xF] ) number >>= 4 else: while number != -1: rlist.append( _digits[number & 0xF] ) number >>= 4 return ''.join(rlist) This was faster for positive numbers. For negative numbers yours was faster, but my version handles those numbers different. Your version fails for Large numbers since hex( long ) returns something like "0xFFFL" instead of "0xfff". > Cheers - Adam Cheers :) - eth From pydecker at gmail.com Sun Mar 12 09:29:33 2006 From: pydecker at gmail.com (Peter Decker) Date: Sun, 12 Mar 2006 09:29:33 -0500 Subject: Cheese Shop: some history for the new-comers In-Reply-To: <44142CAA.9080407@pollenation.net> References: <44126523$0$1016$afc38c87@news.optusnet.com.au> <44141D59.6050806@pollenation.net> <4414234F.7020605@pollenation.net> <44142CAA.9080407@pollenation.net> Message-ID: On 3/12/06, Tim Parkin wrote: > freinds and colleagues both online and off.. Some of whom are python > programmers, most not. Without a budget for 'comprehensive testing' then > the next best thing is asking people, at least you'll generally get rid > of the big bloopers.. it's typically referred to as guerilla testing and > whilst not scientific, it's better than nothing at all. I consider myself a Python developer, and if I saw a 'Developers' link on a Python site, it would seem obvious that it would be something that might interest me. It would not occur to me that this referred to people who are developing the language itself. -- # p.d. From vinjvinj at gmail.com Thu Mar 23 12:37:13 2006 From: vinjvinj at gmail.com (vj) Date: 23 Mar 2006 09:37:13 -0800 Subject: How to find out the next Friday using RelativeDateTime Message-ID: <1143135433.419508.52850@z34g2000cwc.googlegroups.com> I'm doing: a = now() delta = ReltaiveDateTime(days=+6, weekday(mx.DateTime.Friday, 0)) Next Friday: a+delta a: march 23 a+delta: Gives me March 31st and not March 24th Any ideas? From dale at riverhall.nospam.co.uk Wed Mar 29 06:55:21 2006 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Wed, 29 Mar 2006 12:55:21 +0100 Subject: sending ctrl C to a program References: <1143598503.249847.207620@j33g2000cwa.googlegroups.com> Message-ID: s99999999s2003 at yahoo.com wrote: > hi > i have a program that works very similar to tail -f in Unix > It will need a Ctrl-C in order to break out of the program. > I wish to run this program using python (either thru os.system() or > some other subprocess modules) and how can i pass Ctrl-C to this > program to terminate it in python? > thanks Isn't SIGINT the same as ctrl-c? So something like import os os.kill(1234, 2) would send ctrl-c to process 1234. If you just want the process to quit, you could probably just send it a SIGTERM, which is signal 15. -- Dale Strickland-Clark Riverhall Systems - www.riverhall.co.uk We're recruiting programmers. Please see the web site. From lucaberto at libero.it Tue Mar 7 09:06:17 2006 From: lucaberto at libero.it (luca72) Date: 7 Mar 2006 06:06:17 -0800 Subject: Pyserial again In-Reply-To: References: <1141661808.753184.157150@e56g2000cwe.googlegroups.com> <1141665448.418740.167910@i40g2000cwc.googlegroups.com> <120ossf55scsj8b@corp.supernews.com> <1141675566.162480.148260@v46g2000cwv.googlegroups.com> <1141681967.017912.180250@j33g2000cwa.googlegroups.com> <1141721704.444044.212620@p10g2000cwp.googlegroups.com> Message-ID: <1141740377.297085.55300@z34g2000cwc.googlegroups.com> def OnButton1Button(self, event): ser = serial.Serial(0) > ser.baudrate = 9600 > ser.parity = serial.PARITY_ODD > ser.stopbits = serial.STOPBITS_TWO > ser.bytesize =serial.EIGHTBITS > ser.setRTS(level = 0) > ser.setDTR(level = 0) > ser.timeout = 1 > ser.readline() no code before Regards Luca From johnjsal at NOSPAMgmail.com Fri Mar 31 18:47:10 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 31 Mar 2006 18:47:10 -0500 Subject: a simple regex question In-Reply-To: <442dbe42$0$11647$c3e8da3@news.astraweb.com> References: <442dbe42$0$11647$c3e8da3@news.astraweb.com> Message-ID: <442dc0b8$0$11235$c3e8da3@news.astraweb.com> John Salerno wrote: > Ok, I'm stuck on another Python challenge question. Apparently what you > have to do is search through a huge group of characters and find a > single lowercase character that has exactly three uppercase characters > on either side of it. Here's what I have so far: > > pattern = '([a-z][A-Z]{3}[a-z][A-Z]{3}[a-z])+' > print re.search(pattern, mess).groups() > > Not sure if 'groups' is necessary or not. > > Anyway, this returns one matching string, but when I put this letter in > as the solution to the problem, I get a message saying "yes, but there > are more", so assuming this means that there is more than one character > with three caps on either side, is my RE written correctly to find them > all? I didn't have the parentheses or + sign at first, but I added them > to find all the possible matches, but still only one comes up. > > Thanks. A quick note: I found nine more matches by using findall() instead of search(), but I'm still curious how to write the RE so that it works with search, especially since findall wouldn't have returned overlapping matches. I guess I didn't write it to properly check multiple times. From sjuranic at gmail.com Wed Mar 1 11:22:51 2006 From: sjuranic at gmail.com (Steve Juranich) Date: Wed, 01 Mar 2006 09:22:51 -0700 Subject: Accessing 'mangled' class attrbutes References: <1141226955.820389.87860@z34g2000cwc.googlegroups.com> Message-ID: Gerard Flanagan wrote: > I would like to do the following: > > from elementtree.SimpleXMLWriter import XMLWriter > > class HtmlWriter(XMLWriter, object): > def write_raw(self, text): > super( HtmlWriter, self ).flush() > super( HtmlWriter, self ).__write(text) > > but because of the name-mangling caused by '__write' I get: > > AttributeError: 'super' object has no attribute '_HtmlWriter__write'. > > Is there any simple way round this situation in general? > > (I just want to write out a HTML 'DOCTYPE' declaration) Try: (not the Python keyword, but a directive to you) super(HtmlWriter, self)._XMLWriter__write(text) In general, to access the name-mangled members, simply add _ to the front of the member name and you should be able to get at it. But be careful, since this is a reference to the base class, so if it's inherited from some other class, you'll need to know from which class the member is inherited. HTH -- Steve Juranich Tucson, AZ USA From erniedude at gmail.com Thu Mar 30 16:17:49 2006 From: erniedude at gmail.com (Ernesto) Date: 30 Mar 2006 13:17:49 -0800 Subject: Terminating a subprocess question In-Reply-To: <1143649900.667952.15410@t31g2000cwb.googlegroups.com> References: <1143649900.667952.15410@t31g2000cwb.googlegroups.com> Message-ID: <1143753469.243889.101110@t31g2000cwb.googlegroups.com> Ernesto wrote: > I'm opening a telnet session with the subprocess call below. I then > wait ten seconds and attempt to terminate the telnet window I created. > Unfortuantely, the telnet window remains after the 'TerminateProcess" > call below. This software works great for opening an executable > directly (i.e. Handle = subprocess.Popen("myProgram.exe), but here I'm > using the Windows 'start' command inside, which I think has an effect. > > > Is there another way I can force termination of the telnet session I > create ? > > # CODE STARTS HERE > > TSS_Log_Path = "C:\\Log_Outputs\\TSS_Log_Test.txt" > TSS_Handle = subprocess.Popen("start telnet.exe -f " + TSS_Log_Path + " > localhost 6000",shell=True) > time.sleep(10) > ctypes.windll.kernel32.TerminateProcess(int(TSS_Handle._handle), -1) # > Terminate the TSS_Log > > # END CODE Actually, the original answer I was looking for to for a "hard close" of telnet in Windows is: TSS_Handle = subprocess.Popen("TASKKILL /F /IM telnet.exe", shell=True) It is almost definitely true though that it is safer to use telnetlib. I just don't have the time to adjust my entire huge application at the moment. Thanks all. From fake at nospam.no Mon Mar 6 18:13:21 2006 From: fake at nospam.no (Blackbird) Date: Tue, 7 Mar 2006 00:13:21 +0100 Subject: %r References: <75-dnc5y7fLN-ZHZRVnzvA@telenor.com> Message-ID: Fredrik Lundh wrote: > "Blackbird" wrote: > >>>> [...] >>> >>>>>> a = 'I don\'t think so' >>>>>> print '%r' % a >>> "I don't think so" >>>>>> a = r'I don\'t think so' >>>>>> print "'%s'" % a >>> 'I don\'t think so' >> >> Excellent counterexample. Can something like this happen for other >> things than quotes? > >>>> a = '\377' >>>> print '%r' % a > '\xff' >>>> a = r'\377' >>>> print "'%s'" % a > '\377' > > I still recommend looking up %s and %r and str() and repr() in the > documentation. it's not hard to understand what they do, and that > approach works a bit better than cargo cult programming. By "cargo cult programming", do you mean actually *running* the code? Noooo, no, no. I *write* code. I don't *run* code any longer. A long life has thought me that the awakenings you are in for, by running code, are rude and only rude. Blackbird From paul at boddie.org.uk Fri Mar 31 08:50:31 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 31 Mar 2006 05:50:31 -0800 Subject: How to search HUGE XML with DOM? References: <1143803831.939208.190850@v46g2000cwv.googlegroups.com> <494jgvFmvnu9U1@uni-berlin.de> Message-ID: <1143813031.319440.214590@i39g2000cwa.googlegroups.com> Diez B. Roggisch wrote: > > the xml.dom.minidom object is too slow when parsing such a big XML file > > to a DOM object. while pulldom should spend quite a long time going > > through the whole database file. How to enhance the searching speed? > > Are there existing solution or algorithm? Thank you for your > > suggetion... > > I've told you that before, and I tell you again: RDBMS is the way to go. We've lost some context from the original post that may be relevant here, but if populating what the original questioner calls "the database" is an infrequent operation, then an RDBMS probably is the way to go, in general. On the other hand, if a lot of parsing has to happen in order to perform a search, such parsing would probably incur a lot of overhead from SQL inserts that wouldn't be particularly desirable. > There might be XML-parsers that work faster - I suppose cElementTree can > gain you some speed - but ultimately the problems are inherent in the > representation as DOM: no type-information, no indices, no nothing. Just a > huge pile of nodes in memory. Well, I would hope that W3C DOM operations like getElementById would be supported by some index in the implementation: that would make some of the searches mentioned by the questioner fairly rapid, given enough memory. > So all searches are linear in the number of nodes. Of course you might be > able to create indices yourself, even devise a clever scheme to make using > them as declarative as possible. But that would in the end mean nothing but > re-creating RDBMS technology - why do that, if it's already there? I agree that careful usage of RDBMS technology would solve the general problems of searching large amounts of data, but the stated queries should involve indexes and be fairly quick. Paul From fredrik at pythonware.com Fri Mar 31 03:14:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 31 Mar 2006 10:14:32 +0200 Subject: Doc suggestions (was: Why "class exceptions" are not deprecated?) References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com><34bb7f5b0603290859k7738e253v2c9aec2dae93aff5@mail.gmail.com><1143733663.880817.244160@z34g2000cwc.googlegroups.com> Message-ID: > 1) dear lazyweb/lazynet: does anyone have some time to spare on figuring > out how to log into infogami from a simple python script. standard library > only, preferrably. nevermind. the hack that didn't work yesterday did did work today. must have been a bad cookie day. From amichail at gmail.com Sun Mar 19 02:33:18 2006 From: amichail at gmail.com (Amir Michail) Date: 18 Mar 2006 23:33:18 -0800 Subject: python library for web discussions Message-ID: <1142753598.098579.14080@z34g2000cwc.googlegroups.com> Hi, I'm building something like digg/reddit and would like to allow people to have discussions on various items. Is there a simple lightweight python library that I can use (as opposed to a heavyweight web framework)? Although not necessary, some sort of scoring/moderation mechanism would be good also (e.g., like reddit/slashdot). Amir From tim at pollenation.net Tue Mar 28 06:03:27 2006 From: tim at pollenation.net (Tim Parkin) Date: Tue, 28 Mar 2006 12:03:27 +0100 Subject: New Python logo in high resolution format In-Reply-To: <442915E4.9030009@sweetapp.com> References: <1143128619.670174.282160@t31g2000cwb.googlegroups.com> <1143226189.547274.90720@t31g2000cwb.googlegroups.com> <1143253157.4203.20.camel@localhost.localdomain> <442915E4.9030009@sweetapp.com> Message-ID: <442917FF.9040409@pollenation.net> Brian Quinlan wrote: >The new Python logo is available in high-resolution format here: >http://tinyurl.com/n4rge > >Cheers, >Brian > > Thats the old logo, the new logo is at the same address but swap the last url segment from 'logo' to 'newlogo' There still isn't a 'usage' guide for the new logo but I'll get onto one soon hopefully. Tim Parkin From jess.austin at gmail.com Sat Mar 4 13:58:44 2006 From: jess.austin at gmail.com (jess.austin at gmail.com) Date: 4 Mar 2006 10:58:44 -0800 Subject: do design patterns still apply with Python? References: <8SINf.1718$No6.40137@news.tufts.edu> <1141394593.588174.321660@z34g2000cwc.googlegroups.com> Message-ID: <1141498724.068390.232060@z34g2000cwc.googlegroups.com> msoulier wrote: > I find that DP junkies don't tend to keep things simple. +1 QOTW. There's something about these "political" threads that seems to bring out the best quotes. b^) From bj_666 at gmx.net Sat Mar 25 16:57:48 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 25 Mar 2006 22:57:48 +0100 Subject: (not really) randon ideas References: <1143320266.676215.253250@j33g2000cwa.googlegroups.com> Message-ID: In <1143320266.676215.253250 at j33g2000cwa.googlegroups.com>, oluoluolu wrote: > I have been programming in Python for many years, and I generally have > run into alot of the same problems repeatedly. > > What is the consensus on these ideas please? > > * enums There's a cookbook recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486 And a package in the Chesseshop: http://cheeseshop.python.org/pypi/enum/0.4.1 > * constants People tend to write the names of constants all uppercase. Example:: ANSWER = 42 Ciao, Marc 'BlackJack' Rintsch From kent at kentsjohnson.com Thu Mar 2 20:51:49 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 02 Mar 2006 20:51:49 -0500 Subject: setattr question In-Reply-To: <1141335149.855403.261510@e56g2000cwe.googlegroups.com> References: <1141318090.569997.247760@z34g2000cwc.googlegroups.com> <4407355d$0$10756$636a55ce@news.free.fr> <1141335149.855403.261510@e56g2000cwe.googlegroups.com> Message-ID: <44079c86$1_3@newspeer2.tds.net> Gerard Flanagan wrote: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/86900 > > mais il utilise 'apply', qui est...blah > > I was trying to implement the factory pattern. > The recipe above uses 'apply' which is deprecated according to the > docs, and I suppose I was curious how to do the same sort of thing > without 'apply'. Apply has been replaced by 'extended call syntax', that is why it is deprecated. Instead of return apply(self._function,_args,_kargs) write return self._function(*_args, **_kargs) Kent From johnjsal at NOSPAMgmail.com Wed Mar 8 14:02:32 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Mar 2006 19:02:32 GMT Subject: PyCon2006 - will the content be available for download? In-Reply-To: <440f25e1$0$38617$edfadb0f@dread12.news.tele.dk> References: <1141824493.358952.106780@i40g2000cwc.googlegroups.com> <440EDD81.9040708@mxm.dk> <1141832817.145771.153870@u72g2000cwu.googlegroups.com> <1141839254.779163.27290@i39g2000cwa.googlegroups.com> <440f25e1$0$38617$edfadb0f@dread12.news.tele.dk> Message-ID: Max M wrote: > abcd wrote: >> well actually, the site looked promising...only problem is no talks >> have audio, video or handouts available (at least right now). >> >> oh well. >> > > You really need to not give up so fast. > > http://us.pycon.org/talks > > makes it possible to search those with audio (TalkFlags - audio-yes): > > http://us.pycon.org/zope/talks/talksRoster?year%3Alist=&day%3Alist=&track%3Alist=&title=&authors=&abstract=&flags%3Alist=audio-yes&order=Sequence > > > Then most presentations with audio has several audio formats you can > download. > I tried it too. There don't seem to be any audios for 2006, which I think is what the OP was interested in as well. From python.list at tim.thechases.com Fri Mar 3 23:18:05 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 03 Mar 2006 22:18:05 -0600 Subject: stripping spaces in front of line In-Reply-To: <1141444890.389188.140870@i40g2000cwc.googlegroups.com> References: <1141444890.389188.140870@i40g2000cwc.googlegroups.com> Message-ID: <440914FD.7080909@tim.thechases.com> > wish to ask a qns on strip > i wish to strip all spaces in front of a line (in text file) > > f = open("textfile","rU") > while (1): > line = f.readline().strip() > if line == '': > break > print line > f.close() Yes, that would be a way to do it. > in "textfile", i added some spaces in and then ran the code, it prints > out the lines without the spaces in front. I double checked "textfile" > and it does contains some lines with spaces in front. > Is it true that "readline().strip()" perform the removing of spaces in > front of a line as well? Am I missing something here? You've just written a program that does exactly what you ask, and shown to yourself that *yes*, calling "strip()" does indeed strip off whitespace. You state "it prints out the lines without the spaces in front". Yup...I'd guess that's pretty strong evidence that "readline().strip()" performs the removing of spaces in front of a line as well. > Is it documented anywhere? Run a python interpreter shell. >>> help("".strip) >>> help("".rstrip) >>> help("".lstrip) This within-the-interpreter is one of my favorite language features in Python (and maddening when 3rd-party library developers don't document everything as well as the base modules are) -tkc From TheExpert at ExpertHumor.com Thu Mar 30 23:48:43 2006 From: TheExpert at ExpertHumor.com (Expert Humor) Date: 31 Mar 2006 04:48:43 GMT Subject: Amnesty for illegal immigrants will not happen this time..................... Message-ID: <74658633006@free.teranews.com> Our politicians lead the league in all talk, no action. Is blowing us some sunshine good enough? Read what The Expert thinks: http://www.ExpertHumor.com/ *** Free account sponsored by SecureIX.com *** *** Encrypt your Internet usage with a free VPN account from http://www.SecureIX.com *** From andreas at nospam.openrts.org Thu Mar 30 13:34:53 2006 From: andreas at nospam.openrts.org (Andreas R.) Date: Thu, 30 Mar 2006 20:34:53 +0200 Subject: SimpleXMLRPCServer Message-ID: Hello everyone, I'm doing some experiments with the SimpleXMLRPCServer in Python, and I've found it to be an excellent way to do high-level network operations. However, is there a way to enable "two-way" communication using XML-RPC? By that I mean, can the server contact all the clients? Thanks in advance. - Andreas R. www.openrts.org - Open Source RTS game From http Fri Mar 31 23:40:52 2006 From: http (Paul Rubin) Date: 31 Mar 2006 20:40:52 -0800 Subject: Pickle or Mysql References: <1143864315.283697.20970@v46g2000cwv.googlegroups.com> <7xhd5drk2d.fsf@ruckus.brouhaha.com> <1143866226.807178.239190@z34g2000cwc.googlegroups.com> Message-ID: <7xwte952nf.fsf@ruckus.brouhaha.com> amaltasb at gmail.com writes: > So, Is Shelve a perfect solution (besides Mysql), to store large > key/value pairs, and which are updated frequently by multiple clients. No, shelve is for use within a single process. With multiple clients and frequent updates, you need a real database and some knowledge about how to use one. From irvine.david at gmail.com Wed Mar 8 07:31:21 2006 From: irvine.david at gmail.com (dirvine) Date: 8 Mar 2006 04:31:21 -0800 Subject: wxPython cross platform taskbar Message-ID: <1141821081.003706.207050@p10g2000cwp.googlegroups.com> Hi All Does anyone have any peice of wxPython code thats cross platform and allows an app to be minimised in the system tray. I am hoping for windows/kde/gnome/darwin if possible. I have been playing about and have a couple of systems that nearly get there but not quite. I would llike to create an app that does this in the way limewire/skype etc. do it Hope you can help David Heres sample code that nearly gets there I think - it appears to work on ubuntu/gnome import wx ICON_STATE = 0 BLINK_STATE = 0 ID_ICON_TIMER = wx.NewId() class TaskBarApp(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, -1, title, size = (1, 1), style=wx.FRAME_NO_TASKBAR|wx.NO_FULL_REPAINT_ON_RESIZE) self.tbicon = wx.TaskBarIcon() icon = wx.Icon('yellow.ico', wx.BITMAP_TYPE_ICO) self.tbicon.SetIcon(icon, '') #wx.EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarLeftDClick) #wx.EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarRightClick) self.tbicon.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarLeftDClick) self.tbicon.Bind(wx.EVT_TASKBAR_RIGHT_UP, self.OnTaskBarRightClick) self.Bind(wx.EVT_TIMER, self.BlinkIcon, id=ID_ICON_TIMER) self.Show(True) def OnTaskBarLeftDClick(self, evt): global ICON_STATE try: self.icontimer.Stop() except: pass if ICON_STATE == 1: icon = wx.Icon('yellow.ico', wx.BITMAP_TYPE_ICO) self.tbicon.SetIcon(icon, 'Yellow') ICON_STATE = 0 else: self.SetIconTimer() ICON_STATE = 1 def OnTaskBarRightClick(self, evt): try: self.icontimer.Stop() except: pass self.tbicon.Destroy() self.Close(True) wx.GetApp().ProcessIdle() #def OnTaskBarRightClick(self, evt): # self.Close(True) # wx.GetApp().ProcessIdle() def SetIconTimer(self): self.icontimer = wx.Timer(self, ID_ICON_TIMER) wx.EVT_TIMER(self, ID_ICON_TIMER, self.BlinkIcon) self.icontimer.Start(1000) def BlinkIcon(self, evt): global BLINK_STATE if BLINK_STATE == 0: icon = wx.Icon('red.ico', wx.BITMAP_TYPE_ICO) self.tbicon.SetIcon(icon, 'Red') BLINK_STATE = 1 else: icon = wx.Icon('black.ico', wx.BITMAP_TYPE_ICO) self.tbicon.SetIcon(icon, 'Black') BLINK_STATE = 0 class MyApp(wx.App): def OnInit(self): frame = TaskBarApp(None, -1, ' ') frame.Center(wx.BOTH) frame.Show(False) return True def main(): app = MyApp(0) app.MainLoop() if __name__ == '__main__': main() From rune.strand at gmail.com Tue Mar 28 18:25:43 2006 From: rune.strand at gmail.com (Rune Strand) Date: 28 Mar 2006 15:25:43 -0800 Subject: Convert Word .doc to Acrobat .pdf files In-Reply-To: <1143123734.158567.97310@i39g2000cwa.googlegroups.com> References: <1143123734.158567.97310@i39g2000cwa.googlegroups.com> Message-ID: <1143588342.984282.192460@e56g2000cwe.googlegroups.com> kbperry wrote: > Questions: > Does Acrobat Pro, have some way to interface with it command-line (I > tried searching, but couldn't find anything)? Is there any other good > way to script word to pdf conversion? > > Note: The word documents do contain images, and lots of stuff besides > just text. The Acrobat Distiller installs (or van install) a Word VBS macro which allows Word to Save As .PDF. It's easy to call from Python: doc = "somefile.doc" import win32com.client # Create COM-object wordapp = win32com.client.gencache.EnsureDispatch("Word.Application") wordapp.Documents.Open(doc) wordapp.Run("'!CreatePDFAndCloseDoc") # the name of the macro for Acrobat 6.0 wordapp.ActiveDocument.Close() wordapp.Quit() You'll probably wrap this in more logic, but it works. From http Sun Mar 26 15:30:22 2006 From: http (Paul Rubin) Date: 26 Mar 2006 12:30:22 -0800 Subject: wired md5 hashing problem References: Message-ID: <7xhd5lj6e9.fsf@ruckus.brouhaha.com> Matthias G?ntert writes: > i am in the process of writing a python script to backup my data. Now I > would like to implement md5/sha1 hashes. Try editing as follows: change > f = open(fname, "rb") > while 1: > block = f.read(1024*1024) > if not block: > break > # generate the hash > m.update(block) > f.close() to: f = open(fname, "rb") nbytes = 0 while 1: block = f.read(1024*1024) nbytes += len(block) if not block: break # generate the hash m.update(block) f.close() print '%d bytes processed' As Adam DePrince noticed, the md5 checksum you generated was that of an empty file. So the above should tell you whether you're actually processing any input; if you don't get the expected number of bytes, debug from there. From dananrg at yahoo.com Thu Mar 2 16:45:35 2006 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: 2 Mar 2006 13:45:35 -0800 Subject: Best python module for Oracle, but portable to other RDBMSes References: <1140818561.458171.237850@p10g2000cwp.googlegroups.com> <1140826717.186051.261430@i39g2000cwa.googlegroups.com> <1141242710.730153.279490@z34g2000cwc.googlegroups.com> Message-ID: <1141335935.848026.102320@u72g2000cwu.googlegroups.com> > If you actually get a suffixed L in the resulting text file, you > are using a strange way to convert your data to text. You aren't > simply printing lists or tuples are you? Then other types, such as > datetime objects will also look bizarre. (Not that the ancient > odbc would support that...) > You might want to look at the csv module for text export. Thanks Magnus. I didn't know there was a csv module. Here's how I'm getting the suffixed "L" import dbi, odbc # Import ODBC modules connectString = 'odbc_con_name/username/password' dbc = odbc.odbc(connectString) # Connect to Oracle cursor = dbc.cursor() # Create cursor sql = "select statement here..." # Define SQL statement cursor.execute(sql) # Execute sql statement allRecords = cursor.fetchall() # Fetch all returned records into a list of tuples numRecords = len(allRecords) # Get num of records returned by the query # Note: I'm leaving out the for loop for this example... # Print first record: print allRecords[0] >>> (872L, 'ACTIVE', , , None, '1.0.0.0', None, None, None) # Convert first tuple to a list so I have a mutable object recordList = list(allRecords[0]) # Print new list print recordList >>> [872L, 'ACTIVE', , , None, '1.0.0.0', None, None, None] # Convert long integer to short integer (int) to get rid of the "L" recordList[0] = int(recordList[0]) # Print list with changed item. No more "L" print recordList[0] >>> [872, 'ACTIVE', , , None, '1.0.0.0', None, None, None] # The End Are you saying I'm getting the "L" as an artifact of printing? From fredrik at pythonware.com Mon Mar 13 03:12:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Mar 2006 09:12:17 +0100 Subject: python crashes in Komodo References: <1142156538.647430.318350@z34g2000cwc.googlegroups.com> Message-ID: "swisscheese" wrote: > Using the Komodo IDE under XP I often get "python.exe has encountered a > problem and needs to close". Running python direct on the same app > gives a list index out of bounds error. Any ideas how to get Komodo to > give the proper error? is your application using any non-standard (i.e. non-bundled) C extensions ? From deets at nospam.web.de Mon Mar 13 05:32:43 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 13 Mar 2006 11:32:43 +0100 Subject: Implement EJBs in Python/Jython References: <1142242969.712821.280720@j33g2000cwa.googlegroups.com> Message-ID: <47l02pFg5midU1@uni-berlin.de> reinsn wrote: > Hi, > > I'd like to know, if it's possible to implement EJB bean classes in > Python. I mean, Jython provides to possible to create *.class files > from python modules. How must my python module look like to create a > valid enterprise bean class from it. You have to compile a class that implements the EJB-Interface. Look for examples that do that for other classes like struts actions, and perform accordingly. Diez From python.list at tim.thechases.com Tue Mar 7 08:56:46 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 07 Mar 2006 07:56:46 -0600 Subject: Getting File Permissions In-Reply-To: <1141738207.892095.56780@p10g2000cwp.googlegroups.com> References: <1141738207.892095.56780@p10g2000cwp.googlegroups.com> Message-ID: <440D911E.7050801@tim.thechases.com> > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'octal' is not defined > > Since I am new to python, can any one help me to solve this error? Looks like you just want the oct() function (not "octal()") >>> [x for x in dir(__builtins__) if x.lower().find("oct") != -1] ['oct'] The __builtins__ will tell you what functions python supports natively, and you can query against this list for patterns, as done above. -tkc From eddie at holyrood.ed.ac.uk Fri Mar 10 08:43:14 2006 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 10 Mar 2006 13:43:14 +0000 (UTC) Subject: A better RE? References: <1141994336.538970.162480@i39g2000cwa.googlegroups.com> Message-ID: "Jim" writes: >Eddie Corns wrote: >> Just a small point - what does "in order" mean here? if it means that eg 1362 >> is not valid then you're stuck because it's context sensitive and hence not >> regular. >I'm not seeing that. Any finite language is regular -- as a last >resort you could list all ascending sequences of 7 or fewer digits (but >perhaps I misunderstood the original poster's requirements). No, that's what I did. Just carelessnes on my part, time I had a holiday! Eddie From om at oliviermigeon.com Sat Mar 11 14:53:43 2006 From: om at oliviermigeon.com (Olivier) Date: Sat, 11 Mar 2006 20:53:43 +0100 Subject: Advice for creating a web app In-Reply-To: <0001HW.C038D3550042CC99F0488550@news.individual.de> References: <0001HW.C038D3550042CC99F0488550@news.individual.de> Message-ID: <441329e4$0$19112$626a54ce@news.free.fr> Hi there, Jumping until blue a ?crit : > I have a number of files, mostly text files formatted using Markdown > syntax but also pdfs and other types of files, that are stored in a > folder hierarchy and I want to develop a web application where I can > brows, view and search these files. The documents can be > cross-linked. > > Currently I use a basic CGI to view/format the markdown files but I > don't know if I should continue to make my own system or if I should > take advantage of some existing framework. > > My requirements are: ... You may be interested in pyblosxom (http://pyblosxom.sourceforge.net/). It's filesystem based, allows different input formats (html, rest, plain text, I don't know about "Markdown syntax"), allows also to serve what they call static files (like your pdfs), and you can plug some search capacities (for instance, a wrap around grep). I used to run it behind apache with cgi, but it should be possible to use it with a lightweight-no install web server. HTH, Olivier From andre.roberge at gmail.com Sat Mar 4 19:04:01 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 4 Mar 2006 16:04:01 -0800 Subject: Passing a method indirectly In-Reply-To: <1141516407.480315.22400@e56g2000cwe.googlegroups.com> References: <1141516407.480315.22400@e56g2000cwe.googlegroups.com> Message-ID: <1141517041.429132.313610@p10g2000cwp.googlegroups.com> swisscheese wrote: > I'm trying to write a function that takes an arbitrary object and > method. > The function applies the method to the object (and some other stuff). > I get error "Test instance has no attribute 'method' " > How can I make this work? > > def ObjApply (object,method): > object.method () > > class Test: > def test1 (self): print "Hello" > def test2 (self): > ObjApply (self,self.test1) > > ta = Test () > ta.test2 () You need to add one line (2nd one below). def ObjApply (object, method): object.method = method object.method() class Test: def test1 (self): print "Hello" def test2 (self): ObjApply (self, self.test1) ta = Test () ta.test2 () Andr? From duncan.booth at invalid.invalid Thu Mar 30 12:24:49 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Mar 2006 17:24:49 GMT Subject: Set Windows Environment Variable References: <1143723906.146263.136590@i40g2000cwc.googlegroups.com> <1143737936.678171.211010@z34g2000cwc.googlegroups.com> Message-ID: Fuzzyman wrote: > > Magnus Lycka wrote: >> Surely there must be a way to programatically set up the >> environment variables for not yet started processes? I.e. >> doing the same as when you manually change things in the >> control panel. I'm pretty sure many Windows installers do >> that, and while I suppose this is technically a registry >> manipulation, I suspect there is a more direct API somewhere. > > I *believe* that ``SetEnvironmentVariable`` exists in the underlying > windows API, but that it isn't wrapped by the win32api extension. > > I may be wrong. > No, there is a SetEnvironmentVariable call which sets environment variables for the current process. From the documentation: "This function has no effect on the system environment variables or the environment variables of other processes." I don't think it will have much effect on the currently running Python process either since the you just access os.environ and that won't see changes to the system's idea of the environment. Magnus: I took the original question as asking about already running processes. If the question was about processes which have not yet been started then the following may be of use: "Calling SetEnvironmentVariable has no effect on the system environment variables. The user can add or modify system environment variables using the Control Panel. To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message. This allows applications, such as the shell, to pick up your updates. Note that environment variables listed in this key are limited to 1024 characters." This would change the environment for any processes which respond to the WM_SETTINGCHANGE message, and consequently any processes which they start. Window's explorer will then update its environment so that future processes that it starts will pick up the changes. I think that most other applications, including window's CMD.EXE shell won't respond to this message so you wouldn't see the changes in future processes they start. See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/55993 for how to do this from Python. From kent at kentsjohnson.com Fri Mar 3 07:36:58 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 03 Mar 2006 07:36:58 -0500 Subject: object's list index In-Reply-To: References: Message-ID: <440833ba_3@newspeer2.tds.net> William Meyer wrote: > hi, > > I need to get the index of an object in a list. I know that no two objects > in the list are the same, but objects might evaluate as equal. for example > > list = [obj1, obj2, obj3, obj4, obj5] > for object in list: > objectIndex = list.index(object) > print objectIndex > > prints 0, 1, 2, 3, 2 instead of 0, 1, 2, 3, 4 because obj3 == obj5. I could loop > through the list a second time comparing id()'s > > for object in list: > objectIndex = 0 > for i in list: > if id(object) == id(i): > break > objectIndex += 1 > print objectIndex > > but that seems like a real ugly pain. Somewhere, someplace python is keeping > track of the current index in list, does anyone know how to access it? Or have > any other suggestions? > Do you actually need to find the index of an arbitrary object in the list or are you iterating the whole list and you need the list index inside the list? In either case enumerate() is your friend. To find an item by identity: def index_by_id(lst, o): for i, item in enumerate(lst): if item is o: return i raise ValueError, "%s not in list" % o If you just want the index available inside the loop, this replaces your original loop: for i, object in enumerate(lst): print i Kent From nospam at nospam.com Mon Mar 6 16:47:17 2006 From: nospam at nospam.com (3c273) Date: Mon, 6 Mar 2006 13:47:17 -0800 Subject: Opening files without closing them References: <1141598002.402189.275520@i40g2000cwc.googlegroups.com> Message-ID: "Erik Max Francis" wrote in message news:wPCdnSJq7ObP5pbZnZ2dnUVZ_sSdnZ2d at speakeasy.net... > Note quite. The assignment of the resources to its variable needs to be > done before the try: > > f = open(file) > try: > contents = f.read() > finally: > f.close() > Pardon the newbie question, but could you explain why? I have been doing it the same way as the OP and would like to know the difference. Thank you. Louis From elpX at adsihqX.com Thu Mar 9 21:18:15 2006 From: elpX at adsihqX.com (Dr. Pastor) Date: Fri, 10 Mar 2006 02:18:15 GMT Subject: About printing in IDLE? In-Reply-To: References: Message-ID: Many thanks to you all. From steve at REMOVETHIScyber.com.au Sun Mar 5 08:17:42 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 06 Mar 2006 00:17:42 +1100 Subject: how to overload sqrt in a module? References: Message-ID: On Sat, 04 Mar 2006 23:07:12 -0800, Michael McNeil Forbes wrote: > On Fri, 3 Mar 2006, Steven D'Aprano wrote: > >> ... you can do this: >> >> import my_module >> my_module.set_environment("math") # or cmath, or numeric, or whatever >> >> Your my_module will be like this: >> >> # Warning: untested code. >> ENVIRON = None # global variables sometimes have their uses >> >> def f(x): >> if ENVIRON is None: >> raise ValueError("Uninitialised module!") >> # or use a custom exception >> return ENVIRON.sqrt(x) >> >> def set_environment(name): >> global ENVIRON >> ENVIRON = __import__(name) >> >> >> Does this help? > > Yes. However, this raises a question: Is this any different than > directly modifying the globals, or is it just syntactic sugar. The keyword "global" instructs Python to make all references to the following name come from the global namespace. It is the correct way to do it (but not necessarily the *only* correct way, or *always* the correct way). In something as tiny as your example: > def set_environment(name): > globals()['ENVIRON'] = __import__(name) it may not make any practical difference which method you use. But in larger, more complex code, you are creating a rod for your own back. Try running these three functions, and explain the difference in their behaviour. def f1(): global parrot parrot = 3 parrot += 1 print "parrot is %d" % parrot def f2(): globals()["parrot"] = 3 globals()["parrot"] += 1 print "parrot is %d" % parrot def f3(): globals()["parrot"] = 3 parrot += 1 print "parrot is %d" % parrot Directly modifying the globals is playing around with Python's internals. You are allowed to do that, and sometimes it is the right thing to do, otherwise Guido wouldn't have made globals() writable. E.g. you have code where you want -- heaven knows why -- a name to refer to both a local and a global variable. This will work: def func(): x = 5 # x is local globals()['x'] = 3 # but this x is global I don't know whether writing to globals() is guaranteed to work for all variants of Python (CPython, Jython, PyPy, IronPython ... ) or if it is likely to change in Python 3. But even if modifying globals() is officially allowed, it still has a whiff of the sort of code-smell that Joel Spolsky talks about: http://www.joelonsoftware.com/articles/Wrong.html In my opinion, manipulating globals() is one of those things that ring warning bells in my head. It might not be *wrong*, exactly, but I'll want to pay extra attention to any function that does that. -- Steven. From bearophileHUGS at lycos.com Tue Mar 21 08:26:41 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 21 Mar 2006 05:26:41 -0800 Subject: recursive map on nested list References: <1142942495.517738.86490@v46g2000cwv.googlegroups.com> Message-ID: <1142947601.143204.155650@g10g2000cwb.googlegroups.com> I think for most purposes a program like this is short enough: def recur_map2(fun, data): if hasattr(data, "__iter__"): return [recur_map2(fun, elem) for elem in data] else: return fun(data) data = [set([1, 2]), [3], 4, [5, {6:4}, [7, 8]]] print recur_map2(lambda x: x*2, data) Bye, bearophile From tim.peters at gmail.com Wed Mar 29 09:09:19 2006 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 29 Mar 2006 09:09:19 -0500 Subject: any() and all() on empty list? In-Reply-To: References: <1143622860.716668.231370@v46g2000cwv.googlegroups.com> Message-ID: <1f7befae0603290609o7683e29m96fe81235817894b@mail.gmail.com> [Steven D'Aprano] > ... > While the implemented behaviour might be more practical than the > alternatives, it is still worrying paradoxical. If "All sheep are woolly", > then obviously it must also be true that "Any sheep is woolly". More > formally, if all(X), then any(X) -- except for the case of empty X. Hmmm. Right, and this is a very old conundrum in philosophy and logic. You shouldn't expect Python to be the first to solve it to everyone's satisfaction :-) The particular point catching your fancy is formula 17 in: http://www.ditext.com/lejewski/existence.html "LOGIC AND EXISTENCE" Czeslaw Lejewski ... The unrestricted interpretation of the quantifiers seems to remove yet another difficulty from quantification theory. It has been argued by several authors that (16) (?x)(Fx ? ?Fx) and (17) (x)(Fx) ? (?x)(Fx), [i.e., given that some predicate F is true for all x, it follows that there exists an x for which F is true -- or, all(F) implies any(F) - tim] which are valid if the universe is not empty, fail for the empty universe as their truth depends on there being something. When discussing these laws Quine tries to dismiss the case of the empty universe as relatively pointless and reminds us that in arguments worthy of quantification theory the universe is known or confidently believed to be nonempty. This contention, however, does not quite remove our uneasiness particularly as (16) and (17), not unlike (7) and (10), are demonstrable in quantification theory. On considering (16) and (17) we readily admit that these two formulae fail for the empty universe if we understand the quantifiers in accordance with the restricted interpretation. ... Under the unrestricted interpretation, however, (16) and (17) come out to be true irrespective of whether the universe is empty or non-empty. You can read the rest to find out what "the unrestricted interpretation" is, and then decide whether you really want to live in a world that endures that much convolution to make (17) true in an empty universe. It's possible that we live in such a world, but, if so, I'd still like my programming languages to be saner ;-) From michaeltaft at gmail.com Tue Mar 14 23:55:41 2006 From: michaeltaft at gmail.com (mwt) Date: 14 Mar 2006 20:55:41 -0800 Subject: Little Help with Exceptions and ConfigParser In-Reply-To: <44178399_1@newspeer2.tds.net> References: <1142362024.653574.229370@j52g2000cwj.googlegroups.com> <44178399_1@newspeer2.tds.net> Message-ID: <1142398541.103122.131260@z34g2000cwc.googlegroups.com> Would something like this be more useful? def __init__(self, config_file): self.fahdata = fahdata.FAHData() self.INI = ConfigParser.ConfigParser() if os.path.exists(config_file): try: self.INI.read(config_file) except ConfigParser.Error, err: print "Cannot parse configuration file. %s" %err except IOError: print "Problem opening configuration file. %s" %err except Error: print "Problem with with configuration file. %s" %err From invalidemail at aerojockey.com Mon Mar 20 20:38:18 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 20 Mar 2006 17:38:18 -0800 Subject: New-style Python icons In-Reply-To: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> Message-ID: <1142905098.009048.75540@u72g2000cwu.googlegroups.com> and-google at doxdesk.com wrote: > Personally, I *like* the new website look, and I'm glad to see Python > having a proper logo at last! > > I've taken the opportunity to knock up some icons using it, finally > banishing the poor old standard-VGA-palette snake from my desktop. If > you like, you can grab them from: > > http://www.doxdesk.com/img/software/py/icons.png I like 'em. Almost makes me wish I was using Windows. (No it doesn't.) Carl Banks From steve at REMOVETHIScyber.com.au Sat Mar 11 06:59:18 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 11 Mar 2006 22:59:18 +1100 Subject: How to best update remote compressed, encrypted archives incrementally? References: Message-ID: On Sat, 11 Mar 2006 11:46:24 +0100, robert wrote: >> Sounds like a job for any number of already existing technologies, like >> rsync (which, by the way, already uses ssh for the encrypted transmission >> of data). > > As far as I know, rsync cannot update compressed+encrypted into an > existing file(set) ? > I any case with rsync I would have to have a duplicate of the backup > file geometry on the local machine (consuming another magnitude of the > file stuff itself) ? Let me see if I understand you. On the remote machine, you have one large file, which is compressed and encrypted. Call the large file "Archive". Archive is made up of a number of virtual files, call them A, B, ... Z. Think of Archive as a compressed and encrypted tar file. On the local machine, you have some, but not all, of those smaller files, let's say B, C, D, and E. You want to modify those smaller files, compress them, encrypt them, transmit them to the remote machine, and insert them in Archive, replacing the existing B, C, D and E. Is that correct? > Thats why I ask: how to get all these tasks into a cohesive encrypted > backup solution not wasting disk space and network bandwidth? What's your budget for developing this solution? $100? $1000? $10,000? Stop me when I get close. Remember, your time is money, and if you are a developer, every hour you spend on this is costing your employer anything from AUD$25 to AUD$150. (Of course, if you are working for yourself, you might value your time as Free.) If you have an unlimited budget, you can probably create a solution to do this, keeping in mind that compressed/encrypted and modify-in-place *rarely* go together. If you have a lower budget, I'd suggest you drop the "single file" requirement. Hard disks are cheap, less than an Australian dollar a gigabyte, so don't get trapped into the false economy of spending $100 of developer time to save a gigabyte of data. Using multiple files makes it *much* simpler to modify-in-place: you simply replace the modified file. Of course the individual files can be compressed and encrypted, or you can use a compressed/encrypted file system. Lastly, have you considered that your attempted solution is completely the wrong way to solve the problem? If you explain _what_ you are wanting to do, rather than _how_ you want to do it, perhaps there is a better way. -- Steven. From krypto.wizard at gmail.com Wed Mar 15 16:20:52 2006 From: krypto.wizard at gmail.com (krypto.wizard at gmail.com) Date: 15 Mar 2006 13:20:52 -0800 Subject: Python Debugger / IDE ?? In-Reply-To: References: <1142357338.313046.139060@i39g2000cwa.googlegroups.com> Message-ID: <1142457652.412231.26050@v46g2000cwv.googlegroups.com> I like the Pyscripter, is there any Linux version or something of it. Christoph Zwerschke wrote: > krypto.wizard at gmail.com schrieb: > > Is there any editor or IDE in Python (either Windows or Linux) which > > has very good debugging facilites like MS VisualStudio has or something > > like that. > > > > I like SPE but couldn't easily use winPDP. I need tips to debug my code > > easily. > > You can try out PyScripter, a relatively new Python IDE that is > completely free and has nice debugging and unit testing facilities. > > The latest version is available here: > http://mmm-experts.com/Downloads.aspx?ProductID=4&ShowVersionInfo=yes > > -- Christoph From deets at nospam.web.de Thu Mar 2 05:26:25 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 02 Mar 2006 11:26:25 +0100 Subject: Problem with dbi, odbc module and Oracle 9.2 - suffixed "L" with number data type References: <1141293671.315768.186560@i39g2000cwa.googlegroups.com> Message-ID: <46nvjjFc0kofU1@uni-berlin.de> dananrg at yahoo.com wrote: > I was messing around with the native ODBC module (I am using Python in > a Win32 environment), e.g: > > import dbi, odbc > > ...and it seems to meet my needs. I'd rather use a module that comes > natively with Python if it works (don't care about performance in this > particular use case; just that it works). > > The only issue I've had so far is retrieving data from Oracle when an > integer has been defined like: > > number(p) [same thing as number(p,0) evidently] > > This is from a database I didn't design and can't change. Evidently > there are new ways to declare integer data types in Oracle. > > The problem is that the ODBC module suffixes an "L" to any integer > returned that > was defined as data type number(p). For example, an integer stored as: > 56 will be returned as 56L. Actually, it now seems to be doing the > same thing, at least in some cases, for number data types declared as > number(p,s). What gives? Anyone know why this would happen? Well, it is a legal python umber literal. Fire up your python interpreter and do >>> long(1) 1L It simply says that it is a long, not an int (which means 64 rather than 32 bits of precision I think) So - no need to worry. Diez From lists at fabis-site.net Thu Mar 2 18:49:11 2006 From: lists at fabis-site.net (Fabian Steiner) Date: Fri, 03 Mar 2006 00:49:11 +0100 Subject: Printing a file In-Reply-To: <1141298930.103477.70690@u72g2000cwu.googlegroups.com> References: <1141127321.744881.174420@i40g2000cwc.googlegroups.com> <1141298930.103477.70690@u72g2000cwu.googlegroups.com> Message-ID: David Boddie wrote: > Sorry about that. I must have just skipped over the setup() call in > your code. If you're creating highly customized content then I think > you'll always need to think about getting the pages to the printer in > the right order. > > For rich text documents, there's code that does this in the Qt 3 text > drawing demo (see the filePrint() method in the > examples/demo/textdrawing/textedit.cpp file). > > In Qt 4, the demos/textedit demo does this with a lot less code. > > Or are you think of something else? Thank you very much for this hint! Thanks to this example I was able to print out my first pages :) But some questions still remain. At the moment I am using QSimpleRichtext and a personal HTML-File. I had a look at the example.html of textedit.cpp (/usr/share/doc/qt-4.1.1/demos/textedit) and found out that it contains quite a lot of proprietary HTML elements, attributes and CSS style definitions. So far I didn't even know that QSimpleRichText even supports CSS since I couldn't find anything related to this point in the official docs (--> e.g. QStylesheet). Is there any tool out there with which I can write those special HTML files? I am quite familiar with HTML and CSS but I don't want to waste my time with that. Regards, Fabian Steiner From techiepundit at futurepundit.com Tue Mar 21 20:41:29 2006 From: techiepundit at futurepundit.com (Randall Parker) Date: 21 Mar 2006 17:41:29 -0800 Subject: TypeError coercing to Unicode with field read from XML file Message-ID: <1142991689.520777.28860@v46g2000cwv.googlegroups.com> Running Python 2.4.2 on Windows in SPE. I have a very small XML file (see below) that is in UTF-8 and saved by Windows Notepad as such. I'm reading it with minidom. My problem is that once I parse the file with minidom and a field from it to another variable as shown with this line: IPAddr = self.SocketSettingsObj.IPAddress I get this error: File "", line 1, in connect TypeError: coercing to Unicode: need string or buffer, instance found This is the section of code that reads the XML file: ConfigDom = parse(TestSettingsStore.ConfigFileName) #ConfigDom TSSElList = ConfigDom.getElementsByTagName("TargetSocketSettings") NumTargSocks = len(TSSElList) if NumTargSocks > 0: TargetIPAddrList = TSSElList[0].getElementsByTagName("TargetIPAddr") TargetIPPortList = TSSElList[0].getElementsByTagName("TargetIPPort") AddrListLen = len(TargetIPAddrList) PortListLen = len(TargetIPPortList) if AddrListLen > 0 and PortListLen > 0: if TargetIPAddrList[0] <> "" and TargetIPPortList[0] <> 0: StillNeedSettings = False TestSettingsStore.SettingsDictionary['TargetIPAddr'] = TargetIPAddrList[0] TestSettingsStore.SettingsDictionary['TargetIPPort'] = TargetIPPortList[0] This I saved as Unicode from Notepad with encoding UTF-16: 127.0.0.1 43210 this I saved as UTF-8 from Notepad with encoding UTF-8: 127.0.0.1 43210 Both formats create the same error. I'm probably doing something dumb as I've never done XML in Python before. Any ideas what? From Joram.Agten at telindus.be Fri Mar 24 03:28:26 2006 From: Joram.Agten at telindus.be (Joram Agten) Date: Fri, 24 Mar 2006 09:28:26 +0100 Subject: pydoc does not like this file Message-ID: I'm not trying to run py2exe I'm trying to generate a html file with documentation (hence pydoc -w) (python -w doesn't even exist) I have a directory whith 4 files: checkvalue.py <-- the actual source with documentation helperfunctions.py <-- some extra functions setup.py <-- settings file for py2exe build.bat <-- batch file to do the actual build when trying to build the documentation for the whole directory (and not run it 2 times for the 2 py files that need documentation) pydoc choces on the setup.py file joram -----Original Message----- From: Jesus Rivero - (Neurogeek) [mailto:jrivero at python.org.ve] Sent: Thursday, 23 March, 2006 19:47 To: Joram Agten Cc: python-list at python.org Subject: Re: pydoc does not like this file -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 hmmm guess -w should be after python and not after pydoc: python -w c:\python24\Lib\pydoc.py .\setup.py And i also guess you are missing a command after setup.py (if you are using py2exe, that must be the command you are looking for.) so try this: $ python -w c:\python24\Lib\pydoc.py .\setup.py py2exe Best Regards, Jes?s Rivero - (Neurogeek) Joram Agten wrote: > Hello please put me in CC > > I'm trying pydoc as documentation for my projects but I have the > following problem when runnig pydoc on my whole project there is > also a file setup.py (from py2exe) but pydoc gives me the following > for that file: > > [D:\programming\trunk\tecap\joag\checkvalue]python > c:\python24\Lib\pydoc.py -w .\setup.py problem in .\setup.py - > SystemExit: usage: pydoc.py [global_opts] cmd1 [cmd1_opts] [cmd2 > [cmd2_opts] ...] or: pydoc.py --help [cmd1 cmd2 ...] or: pydoc.py > --help-commands or: pydoc.py cmd --help > > error: option -w not recognized > > there are no statements or functions in that file, and also no > documentation anybody has any idea? > > joram -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFEIu09dIssYB9vBoMRAmfOAJ4h9mb5PgD/ZTWdh1VDu6GMvAb5DgCfTpPz 4UgOQcwkH6VhPQpjZI15nW0= =W2ZS -----END PGP SIGNATURE----- From prettyboy988-google at yahoo.com Fri Mar 3 03:13:29 2006 From: prettyboy988-google at yahoo.com (P Boy) Date: 3 Mar 2006 00:13:29 -0800 Subject: Question In-Reply-To: References: Message-ID: <1141373609.628390.263070@t39g2000cwt.googlegroups.com> You may want to read up on http://python.org/doc/faq/installed.html From duncan.booth at invalid.invalid Mon Mar 13 03:40:15 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Mar 2006 08:40:15 GMT Subject: __del__ not called? References: Message-ID: Gregor Horvath wrote: > #!/usr/bin/python > class A(object): > def __init__(self): > print "init" > > def __del__(self): > print "del" > > test1.py > > #!/usr/bin/python > import test > > class B(object): > a = test.A() > > Running test1.py outputs: > > init > > the "del" is missing. > > I suppose the a object should be garbage collected!? No, Python doesn't run the garbage collector when it is exiting. What it does is to delete all the globals from each module in turn. So: C:\Python24>python Python 2.4.2c1 (#66, Sep 21 2005, 15:16:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class A(object): ... def __init__(self): ... print "init" ... def __del__(self): ... print "del called" ... >>> a = A() init >>> ^Z del called C:\Python24> In this case the del method is called as 'a' is deleted, but if you create a circular reference a does not get destroyed: >>> class A(object): ... def __init__(self): ... print "init" ... def __del__(self): ... print "del called" ... >>> a = A() init >>> a.ref = a >>> ^Z C:\Python24> What is less obvious is that new style classes always include circular references, so a class is never detroyed until the garbage collector runs. A.__mro__ is a tuple which includes A, and there is probably something else I've forgotten (for an empty and otherwise unreferenced class getrefcount(oldstyleclass) returns 2, getrefcount(newstyleclass) returns 5). Of course, if your __del__ method actually does get invoked during program exit you have to be pretty careful what you do: the chances are any global variables you used in __del__ have already been destroyed in particular any modules you imported may have been deleted. In short, don't rely on anything much being possible from __del__ called this way. From wkehowski at cox.net Thu Mar 23 13:53:07 2006 From: wkehowski at cox.net (wkehowski at cox.net) Date: 23 Mar 2006 10:53:07 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: <1143134775.887696.5000@z34g2000cwc.googlegroups.com> References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1143024937.827420.104100@i39g2000cwa.googlegroups.com> <20060322141400.1A00.1.NOFFLE@dthierbach.news.arcor.de> <1143110872.284192.325230@u72g2000cwu.googlegroups.com> <20060323134326.C29.0.NOFFLE@dthierbach.news.arcor.de> <1143134775.887696.5000@z34g2000cwc.googlegroups.com> Message-ID: <1143139987.254145.267980@g10g2000cwb.googlegroups.com> Call a wc 'free' if it satisfies the propery that every letter 'a' in it appears only in the form '*a*', and 'anchored' otherwise. What if all wc's are free? How does this affect the DFA? Does it minimize nontrivially? Keep in mind I'm new to DFA theory. Walter Kehowski From jzgoda at o2.usun.pl Sat Mar 4 06:17:08 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sat, 04 Mar 2006 12:17:08 +0100 Subject: Writing an OPC client with Python ? In-Reply-To: <4408aeca$0$12868$626a54ce@news.free.fr> References: <440880b4$0$13692$636a55ce@news.free.fr> <4408A1C8.6080004@websafe.com> <4408aeca$0$12868$626a54ce@news.free.fr> Message-ID: pierlau napisa?(a): >> You can call methods/functions in a .dll using ctypes. >> >> http://starship.python.net/crew/theller/ctypes/ > > I have tried with ctypes. > I acheived to load the library > it works when I use following instructions : > print windll.OPCDAAuto or print cdll.OPCDAAuto > (i see an handle number) > But I can't run the functions? > I there a way to 'see' the inside of the dll > (i.e. to list the methods) ? Look for C header file (*.h) for this library or find docs. -- Jarek Zgoda http://jpa.berlios.de/ From __peter__ at web.de Wed Mar 8 08:38:41 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 08 Mar 2006 14:38:41 +0100 Subject: class variables for subclasses tuple References: <1141809649.911658.90570@p10g2000cwp.googlegroups.com> <1141812400.569624.256460@i39g2000cwa.googlegroups.com> <1141822390.235813.42860@u72g2000cwu.googlegroups.com> Message-ID: alainpoint at yahoo.fr wrote: > In passing, I have another question: where can I read up more on > metaclasses? Well, in "Python in a Nutshell" Alex Martelli manages to pack the practical information that lets you work with metaclasses into just four pages, including a two-page example. You may have seen posts by Alex on c.l.py that are longer... Peter From bignose+hates-spam at benfinney.id.au Thu Mar 30 20:47:12 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 31 Mar 2006 11:47:12 +1000 Subject: Newbie: splitting dictionary definition across two .py files References: <1143766251.793448.191380@i40g2000cwc.googlegroups.com> Message-ID: <87mzf775cv.fsf@rose.polar.local> kar1107 at gmail.com writes: > I'm fairly new to python. I like to define a big dictionary in two > files and use it my main file, build.py > > I want the definition to go into build_cfg.py and build_cfg_static.py. That sounds like a very confusing architecture, and smells very much like some kind of premature optimisation. What leads you to that design? It's very likely a better design can be suggested to meet your actual requirements. -- \ "If you can't annoy somebody there is little point in writing." | `\ -- Kingsley Amis | _o__) | Ben Finney From johnjsal at NOSPAMgmail.com Wed Mar 29 22:15:43 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 29 Mar 2006 22:15:43 -0500 Subject: a hobbyist's dilemma In-Reply-To: References: Message-ID: <442b4e78$0$32270$c3e8da3@news.astraweb.com> Jim Sizelove wrote: > John Salerno wrote: >> Now that I've learned much of Python, I'm sort of stuck with what to do >> with it. I'm not a professional programmer, so I don't really have a use >> for Python now. But I really want to come up with some neat uses for it >> (for fun, and so I don't just start forgetting it right after I learned >> it). > > Here are some other ideas: > > You can find sample code for project ideas at Useless Python > (http://uselesspython.com) and the Python Cookbook > (http://aspn.activestate.com/ASPN/Python/Cookbook/). > > Hang out at the python tutor mailing list > (http://mail.python.org/mailman/listinfo/tutor) and learn from others > and learn by helping others. > > Enjoy your python adventures, > Jim Sizelove Thanks! From joel.hedlund at gmail.com Mon Mar 27 02:22:55 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Mon, 27 Mar 2006 09:22:55 +0200 Subject: OT: unix newbie questions In-Reply-To: <1143287156.026223.320310@i40g2000cwc.googlegroups.com> References: <1143287156.026223.320310@i40g2000cwc.googlegroups.com> Message-ID: > * I'm using the tcsh shell and have no problems with it, but bash seems > more popular - any reason to change? (I don't intend writing many shell > scripts) You can do this in bash: $ python myprog > stdout.txt 2> stderr.txt and have output to sys.stdout and sys.stderr go in separate files. Quite handy for separating output and debugging comments. I believe that this is impossible in tcsh (where you only can do $ python myprog &> stdout_and_stderr.txt to catch stdout and stderr at the same time). Also: bash_completions. It keeps track of arguments and options for commonly used programs and commands. If you type "cd " and hit tab for completions you will only see directories, since bash_completions knows that this is all cd accepts. Don't know if tcsh has anything similar. Cheers, Joel Hedlund From my_email_is_posted_on_my_website at munged.invalid Thu Mar 16 13:17:38 2006 From: my_email_is_posted_on_my_website at munged.invalid (Roedy Green) Date: Thu, 16 Mar 2006 18:17:38 GMT Subject: Xah's Edu Corner: The Concepts and Confusions of Pre-fix, In-fix, Post-fix and Fully Functional Notations References: <1142490052.127055.50130@v46g2000cwv.googlegroups.com> Message-ID: On 15 Mar 2006 22:20:52 -0800, "Xah Lee" wrote, quoted or indirectly quoted someone who said : >e. For example, the in-fix >notation =E2=80=9C(3+(2*5))>7=E2=80=9D is written as =E2=80=9C3 2 5 * + 7 >= >=E2=80=9D, where the Not that Mr. Lee has ever shown much interest in feedback, but you pretty well have stick to vanilla ASCII to get your notation through unmangled on newsgroups. -- Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching. From andreas at nospam.openrts.org Wed Mar 8 01:22:56 2006 From: andreas at nospam.openrts.org (Andreas R.) Date: Wed, 08 Mar 2006 07:22:56 +0100 Subject: asynchat - operation could not complete w/ blocking In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > "Andreas R." wrote: > >> I'm using Python's asynchat module for networking. >> When calling the sendall() method of asynchat, >> I sometimes get the error message "the operation >> could not complete without blocking". > > what sendall method ? to get proper output buffering with asynchat, use Search for sendall here: http://svn.gna.org/viewcvs/openrts/trunk/openrts/client/networksend.py?rev=67&view=markup That's what I was told to use here: http://groups.google.no/group/comp.lang.python/browse_thread/thread/e8615b50ea990a5f/0a30540bd8ec9db5 That's not correct? You can try the version using sendall here: http://svn.gna.org/daily/openrts-snapshot.tar.gz -Andreas www.openrts.org From johnjsal at NOSPAMgmail.com Fri Mar 17 16:11:03 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 17 Mar 2006 21:11:03 GMT Subject: Importing an output from another function In-Reply-To: <1142629118.886810.251200@u72g2000cwu.googlegroups.com> References: <1142626528.204581.179350@v46g2000cwv.googlegroups.com> <1142627019.614450.250540@i40g2000cwc.googlegroups.com> <1142628076.041352.320560@i40g2000cwc.googlegroups.com> <1142629118.886810.251200@u72g2000cwu.googlegroups.com> Message-ID: Byte wrote: > Now what do I do if Func1() has multiple outputs and Func2() requires > them all to give its own output, as follows: You can return them as a tuple: >>> def func1(): output1 = 'hi' output2 = 'bye' return (output1, output2) >>> def func2(data): print data >>> func2(func1()) ('hi', 'bye') > def Func1(): > choice = ('A', 'B', 'C') > output = random.choice(choice) > output2 = random.choice(choice) > return output > return output2 Only the first return statement would run in that code. From sybrenUSE at YOURthirdtower.com.imagination Thu Mar 30 02:17:54 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 30 Mar 2006 09:17:54 +0200 Subject: difference between .cgi and .py References: <1143701879.632741.6220@g10g2000cwb.googlegroups.com> Message-ID: amaltasb at gmail.com enlightened us with: > I am new to python.. I have uploaded few scripts in my cgi-bin > folder, some with extension .cgi and some with .py. > > What is the difference between the two extensions.. None at all, except the way you write them. > which one is more prefered That depends. If you want to hide the fact that you're using Python, use .cgi. If you want to show that, use .py. > do it effects performance ?? Nope. This is all assuming you're using the most widely used webserver Apache. 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 Fri Mar 3 08:48:44 2006 From: gandalf at designaproduct.biz (Laszlo Zsolt Nagy) Date: Fri, 03 Mar 2006 14:48:44 +0100 Subject: Convert dictionary to HTTP POST In-Reply-To: References: <4408084D.4060708@designaproduct.biz> Message-ID: <4408493C.8050901@designaproduct.biz> > > >See urllib.urlencode(). No idea why they don't include it in urllib2 as >well, but there you go. > > >>> from urllib import urlencode > >>> urlencode({'a':'& "Simple string"', 'b': '<>!@#$%^&*()_+='}) >'a=%26+%22Simple+string%22&b=%3C%3E%21%40%23%24%25%5E%26%2A%28%29_%2B%3D' > >>> > > Hmm. urlencode is using quote_plus internally. Looks like there is no difference in the encoding of the apostrophe. I tried to create a very basic form and realized that the problem is NOT with the quoting. I'm writting a program that puts orders into a wholesaler's database. They do not have a programatic interface, so I have to login and post forms using a program. There are some fields that I must not change, so I have to read the value from the HTML source and then post it back. Here is the problem:
The values of some inputs are encoded using html entities. How can I decode a string like "Bessy's cat" in "Bessy's cat"? Thanks, Laszlo From rtilley at vt.edu Tue Mar 7 17:15:31 2006 From: rtilley at vt.edu (rtilley) Date: Tue, 07 Mar 2006 17:15:31 -0500 Subject: Send email notification In-Reply-To: <1141759889.952367.59260@j33g2000cwa.googlegroups.com> References: <1141759889.952367.59260@j33g2000cwa.googlegroups.com> Message-ID: Ernesto wrote: > Is there a special module for mail ? > > I'd like to send an email [to 'n' unique email addresses] from a python > script. from email.MIMEText import MIMEText import email.Utils import smtplib # 'users' is a list of email addys. for u in users: try: print "Sending email to ... ", u f = "FROM_NAME" t = u msg = MIMEText("""MESSAGE BODY OF EMAIL""") msg["Subject"] = "MESSAGE SUBJECT" msg["Message-id"] = email.Utils.make_msgid() msg["From"] = f msg["To"] = t h = "YOUR.SMTP.SERVER" s = smtplib.SMTP(h) s.sendmail(f, t, msg.as_string()) s.quit() except Exception, e: print e From frank at chagford.com Tue Mar 21 00:35:13 2006 From: frank at chagford.com (Frank Millman) Date: 20 Mar 2006 21:35:13 -0800 Subject: Pycrypto - active ?? In-Reply-To: <1hchm5b.1vgq264sk3olaN%aleaxit@yahoo.com> References: <1142804398.710230.117640@j33g2000cwa.googlegroups.com> <1142807299.141313.306980@i40g2000cwc.googlegroups.com> <1142841321.980154.320340@u72g2000cwu.googlegroups.com> <7xslpdl7yg.fsf@ruckus.brouhaha.com> <1142856119.461122.293150@i40g2000cwc.googlegroups.com> <1142861008.662593.172900@t31g2000cwb.googlegroups.com> <1hchm5b.1vgq264sk3olaN%aleaxit@yahoo.com> Message-ID: <1142919313.863978.133190@i40g2000cwc.googlegroups.com> Alex Martelli wrote: > Frank Millman wrote: > ... > > The docs say that if you have any of m2crypto, cryptlib, pycrypto, or > > GMPY installed, it will be used for fast cryptographic operations. I > ... > > However, I have not found an MSW binary for Python 2.4 for any of the > > above packages. TLSLite works ok by itself, but it is noticeably slower > > when transferring large amounts of data. > > There are several Windows binaries of GMPY for 2.4 on sourceforge.net, > optimized for different intel and AMD processors. Since gmpy.sf.net is > gmpy's home, I don't understand what you mean by "have not found". > > > Alex Apologies for the misinformation. You are correct, and I am embarrassed. I have revisited what I did a week ago, and I now recall that I *did* successfully install GMPY, but it made no difference to the speed of TLSLite. I could try to dig deeper by examining the source code of TLSLite, but it is low priority for me at present. The fact that I got SSL/TLS working is a big win, and the speed test was a theoretical exercise. For practical purposes, it is fast enough. Sorry for causing confusion. Frank From mahs at telcopartners.com Fri Mar 24 03:36:57 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Fri, 24 Mar 2006 00:36:57 -0800 Subject: overlapping sets In-Reply-To: <1143183343.525253.251430@i39g2000cwa.googlegroups.com> References: <1143183343.525253.251430@i39g2000cwa.googlegroups.com> Message-ID: kpp9c wrote: > I have a question... and ... whew ... i am gonna be honest, i haven't > the slightest clue how to even start ... i am not sure if i used up all > my good will here or can take a mulligan.. i love to try to at least > post some lame broken code of my own at first... but like i said, not > being a math person i am not even sure how to start or if it is even > possible. > > here's the deal... i have a dictionary that defines some collections.. > like so: > > sets = { ('one') : [0, 4, 7, 9 ], > ('two') : [0, 3, 7, 9 ], > ('three') : [0, 4, 7, 11], > ('four') : [0, 3, 7, 10 ], > ('five') : [0, 4, 7, 10 ], > ('six') : [0, 4, 8, 10 ], > ('seven') : [0, 3, 6, 10], > ('eight') : [0, 3, 6, 9 ], > ('nine') : [0, 3, 7, 11 ], > ('ten') : [0, 5, 7, 10 ] } > > I every time i call this function i would like like it to return a > collection at random, any collection, so long as it has all but one > element that is the same. So if i grab [0, 4, 7, 9 ] as my first set > my next set could be: [0, 3, 7, 9 ], or [0, 4, 8, 9 ], or [0, 4, 7, > 10], or [1, 4, 7, 9 ], since all these sets contain 3 elements in > common with the first, and only one that is new or different... but if > my first run give me: [0, 4, 7, 9 ] i would not get [0, 5, 7, 10 ], > since this is set has 2 elements that are unique. The goal it to move > from set to set to set to set always with a maximum of overlap & common > elements. > > I wonder, if this is even possible, *and* if it can be done with sets > that have as many as 7, 8, or even 9 elements or if this would be too > slow to even attempt. > > cheers, > > kp8 > > [for the record using python 2.3 on a macintosh at the moment] > Here's an example of a possible approach. It uses a naive search algorithm, but it should illustrate the general idea: # Search for a path through the nodes that changes only one member per step nodes = [[0, 3, 6, 10], [0, 5, 7, 10], [0, 3, 7, 11], [0, 4, 8, 10], [0, 4, 7, 11], [0, 3, 7, 9], [0, 3, 7, 10], [0, 4, 7, 10], [0, 3, 6, 9], [0, 4, 7, 9]] try: frozenset except NameError: # 2.3 compatibility, untested from sets import ImmutableSet as frozenset def get_graph(nodes): """From a list of sequences, return a graph, mapping each node to its neighbors - defined as nodes with all but one common element""" graph = dict.fromkeys([frozenset(s) for s in nodes]) for s in graph: neighbor_len = len(s)-1 graph[s] = [t for t in graph if len(s&t)==neighbor_len] return graph def walk_nodes(nodes, walk_length = None): if walk_length is None: walk_length = len(nodes) graph = get_graph(nodes) def add_move(history): for path in history: last_move = path[-1] # remove the last_move from the graph: we can't go there again possible_next = graph.pop(last_move) # look in sequence at the possible neighbors # this is a naive - a better heuristic would perhaps be to # visit neighbors with fewer exits first for next in possible_next: if next in graph: # if the node is still in the paths dict, we haven't # visited it yet, so let's go yield path + [next] # Pick a starting point - naive! history = [graph.keys()[0]], # set up n nested generators, each representing one move depth for move in range(walk_length-1): history = add_move(history) # yield a generator of all paths through the graph of length walk_length # by trial and error, you can find the longest path return history Apparently, there is no path through all 10 nodes: >>> list(walk_nodes(nodes)) [] But there are a couple of 7-node paths: >>> list(walk_nodes(nodes,7)) [[frozenset([0, 9, 3, 6]), frozenset([0, 9, 3, 7]), frozenset([0, 11, 3, 7]), frozenset([0, 11, 4, 7]), frozenset([0, 10, 4, 7]), frozenset([0, 10, 3, 7]), frozenset([0, 10, 3, 6])], [frozenset([0, 9, 3, 6]), frozenset([0, 9, 3, 7]), frozenset([0, 11, 3, 7]), frozenset([0, 11, 4, 7]), frozenset([0, 10, 4, 7]), frozenset([0, 10, 3, 7]), frozenset([0, 10, 5, 7])]] >>> HTH, Michael From paddy3118 at netscape.net Sun Mar 12 03:31:11 2006 From: paddy3118 at netscape.net (Paddy) Date: 12 Mar 2006 00:31:11 -0800 Subject: Python Love :) In-Reply-To: <1142099350.122968.35220@i39g2000cwa.googlegroups.com> References: <1142099350.122968.35220@i39g2000cwa.googlegroups.com> Message-ID: <1142152271.545155.268170@i40g2000cwc.googlegroups.com> Spread the love - tell your Java freinds :-) From sergio at village-buzz.com Mon Mar 6 12:46:48 2006 From: sergio at village-buzz.com (sergio at village-buzz.com) Date: 6 Mar 2006 09:46:48 -0800 Subject: automatic referencing for variables? Message-ID: <1141667208.481756.56600@u72g2000cwu.googlegroups.com> i am SURE i am using the wrong terminology... but what i would like to do is something like this: pageContent=''' {toc} h1. Header Section h2. Date: {metadata:date}'''+date+'''{metatdata} h2. Author: {metadata:author}Len Sweet{metadata} h1. Exegesis {metadata:exegesis}'''+exegesis+'''{metadata} h1. Text Alive {metadata:textalive}'''+textAlive+'''{metadata} h1. Illustrations, Illuminations, Animations: {metadata:illustrations}'''+illustrations+'''{metadata} h1. Worship Resources ''' but rather than have: '''+variable+''' have something a little cleaner.. in php, you can do something like text="this is text where variable = {variable}"; can you do something like that in python? thanks! From dananrg at yahoo.com Mon Mar 20 19:16:22 2006 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: 20 Mar 2006 16:16:22 -0800 Subject: Spidering Hacks for Python, not Perl Message-ID: <1142900182.388650.179350@i40g2000cwc.googlegroups.com> O'Reilly's Spidering Hacks books terrific. One problem. All the code samples are in Perl. Nothing Pythonic. Is there a book out there for Python which covers spidering / crawling in depth? From aleaxit at yahoo.com Sun Mar 26 16:17:18 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Mar 2006 13:17:18 -0800 Subject: Accessing func_name from inside a function References: <1143309619.566327.173640@j33g2000cwa.googlegroups.com> <1hcs34g.1f6lnx81ic59i5N%aleaxit@yahoo.com> Message-ID: <1hct5wu.nl1a63sbhn19N%aleaxit@yahoo.com> Ron Adam wrote: > A "Current" key word would fix this. Or possibly "This" which would be > short for "This object". I think "This" would cause huge confusion, since in other popular language the keyword "this" means (a pointer/reference to) "the instance variable on which the method is being called" -- my use is instead for "the object of the immediate lexically enclosing scope" (a module, class, or function). Implementation wouldn't be trivial in today's CPython, anyway: frames have no references at all to function objects (only to _code_ objects), and class objects don't even exist untill well after their top-level code has long finished running; to make Current possible, these subtle points of semantics would have to be changed in quite a revolutionary way, especially where classes are concerned. Alex From siona at chiark.greenend.org.uk Fri Mar 24 10:58:21 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 24 Mar 2006 15:58:21 +0000 (GMT) Subject: don't understand popen2 References: <4421effd$0$11070$e4fe514c@news.xs4all.nl> <44225c55$0$11064$e4fe514c@news.xs4all.nl> <4422e21a_3@newspeer2.tds.net> Message-ID: Kent Johnson wrote: >Sion Arrowsmith wrote: >> (and please avoid the abuse of raw strings for Windows paths). >Why do you consider that abuse of raw strings? I consider it abuse because it's not what they were invented for. I consider discouraging it to be a good thing in order to reduce the chances of people being bitten by, for instance: >>> os.listdir(r"C:\") File "", line 1 os.listdir(r"C:\") ^ SyntaxError: EOL while scanning single-quoted string and getting all confused on this group. -- \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 michele.petrazzo at TOGLIunipex.it Fri Mar 3 07:23:31 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Fri, 03 Mar 2006 13:23:31 +0100 Subject: Exception not raised - May be the end In-Reply-To: References: <44071622$0$29101$5fc30a8@news.tiscali.it> Message-ID: <4408354b$0$29094$5fc30a8@news.tiscali.it> Sion Arrowsmith wrote: > Michele Petrazzo wrote: >> some days ago I posted here and say that python "forgot" to raise >> an exception, but my code was too long for make some tries >> possible. But now I can reproduce the problem into another, little, >> project: >> >> www.unipex.it/vario/wxFrameSchedule.py >> www.unipex.it/vario/metamenus.py [ ... ] > > It looks like a "wx sandwich" issue to me Yes! Now I think the same > Robin gave a full explanation to someone else having similar problems > on wxPython-users a couple of days ago, but I'm having trouble > finding that. > Yes, I had read it, but I didn't think that was I similar problem! This is the message http://aspn.activestate.com/ASPN/Mail/Message/wxpython-users/3034524 I hope that, like Robin says, this will be changed into 2.7! Thanks a lot for the tip! Michele From niemand.leermann at thomas-guettler.de Mon Mar 13 10:10:33 2006 From: niemand.leermann at thomas-guettler.de (Thomas Guettler) Date: Mon, 13 Mar 2006 16:10:33 +0100 Subject: Which GUI toolkit is THE best? References: <441172c2$1@news1.ethz.ch> Message-ID: Am Fri, 10 Mar 2006 16:10:09 +0100 schrieb Sybren Stuvel: > Thomas Guettler enlightened us with: >> The licence for QT is GPL, this means you cannot use it in >> commercial application. That is why I never looked at it. > > Ehmm... from their website: >From http://www.trolltech.com/products/qt/licensing.html > The Qt Commercial License is the correct license to use for the > construction of proprietary, commercial software. The license allows > you to: > - Build commercial software and software whose source code you > wish to keep private. > - Freely choose licensing for the software you are writing > (Proprietary, Open Source or both). > - Be able to gain access to Qt Solutions, Trolltech support and > commercial-only Qt components such as commercial database > drivers and the Visual Studio Integration on Windows. Have you read all the text? """ Two qualities of the Qt Commercial License should be emphasized: You need it before you start development of proprietary software. You must purchase a Qt Commercial License from Trolltech or from any of its authorized resellers before you start developing. The Commercial license does not allow the incorporation of code developed with the Open Source Edition of Qt into a proprietary product. """ There is a GPL version for Linux. But the GPL does not allow linking with closed source software. -- Thomas G?ttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From fredrik at pythonware.com Fri Mar 3 16:56:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 3 Mar 2006 22:56:35 +0100 Subject: Calculating md5 checksums. References: <47a726d60603031157haece1e0geb7d8898fb77eed0@mail.gmail.com> Message-ID: Rajesh Sathyamoorthy wrote: > How do you calculate the md5 checksum of a file? > > so far i got this, > > import md5 > > obj = md5.new() > file = open( 'filename', 'rb') > data = text.read() > obj.update(data) > checksum = md5.digest() > > Is this correct? Is there anything else i should do before comparing the > checksum with the one provided for the file? the script has some obvious bugs, but nothing you won't discover simply by running the program... (did you try that? what happened?) From __peter__ at web.de Thu Mar 23 03:32:00 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 23 Mar 2006 09:32:00 +0100 Subject: where is os.path.expanduser? References: Message-ID: Kevin F wrote: > where is this code looking for the .imap file? I am on OSX and am not > sure where to put the file it is looking for. > > f = open(os.path.expanduser('~/.imap')) Your interactive interpreter has the answer >>> import os >>> os.path.expanduser("~") '/home/peter' that will most likely differ from the one given above. Peter From grflanagan at yahoo.co.uk Thu Mar 9 16:55:11 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 9 Mar 2006 13:55:11 -0800 Subject: Any python HTML generator libs? In-Reply-To: <1141936438.584242.129220@z34g2000cwc.googlegroups.com> References: <1141936438.584242.129220@z34g2000cwc.googlegroups.com> Message-ID: <1141941311.238760.31110@u72g2000cwu.googlegroups.com> Sullivan WxPyQtKinter wrote: > Hi, everyone. Simply put, what I need most now is a python lib to > generate simple HTML. > > I am now using XML to store my lab report records. I found python > really convinient to manipulate XML, so I want to make a small on-line > CGI program to help my colleagues to build their lab report records > into XML, for storage, HTML display (for others to browse) and search. > > With python's standard lib, the DOM object could realize the XML > storage and search quite easily, but for HTML generation, it is a > great headache. > > I tried to turn to the in-line server-side python script PSP(something > like asp and php) instead of CGI. However, since the report data is > always of very complex data structures, it is really hard to write most > things in-line. For example, a PCR reaction is expected to be shown in > this format or alike on a web browser: > > PCR > Sample: Sm1032 > Operater: SullivanZ > TimeStamp: hh:mm mm-dd-yyyy > Reaction: > Reagent1: > Name:XXXX > Concentration:XXXX mM > Volumn:XXX uL > Reagent2: > ........................ > ........................ > > Since there are hundreds of PCR reaction and other operations in the > lab report, in-line PSP is not a suitable solution. But writing HTML > directly with print statement is a great pain. > > Will XSTL be useful? Is my problem somewho related with XML-SIG? > Looking forward to your precious suggestion. If you don't mind a learning curve, you could use a CherryPy/Picket combination - Picket is an XSLT 'filter' that uses 4Suite to transform XML on the server: http://www.cherrypy.org/wiki/Picket XSLT is powerful but a bit...wearying, at first. Gerard From jstroud at ucla.edu Thu Mar 2 21:01:15 2006 From: jstroud at ucla.edu (James Stroud) Date: Thu, 02 Mar 2006 18:01:15 -0800 Subject: Making a tiny script language using python: I need a string processing lib In-Reply-To: <1141350818.374837.197270@v46g2000cwv.googlegroups.com> References: <1141350818.374837.197270@v46g2000cwv.googlegroups.com> Message-ID: Sullivan WxPyQtKinter wrote: > I do not know if there is any lib specially designed to process the > strings in scipt language. > for example: > I hope to process the string"print a,b,c,d,e "in the form"command > argumentlist" and return: > {'command'='print', > 'argumentlist'=['a','b','c','d','e']} > Are there any lib to implement this? > > > Ideally , the lib should have a function like below: > > def extract(commandstring, splitformat) > > eg: > extract("see#you at tonight","what#whom at when") > return: {"what":"see","whom":"you","when":"tonight"} > > extract("1;2;3;4;5","list[;]") > return: {"list":['1','2','3','4','5']} > > extract("print a,b,c,d,e","command arglist[,]") > return: {"command":"print","arglist":['a','b','c','d','e']} > > extract("fruit:apple~orgrange~pear~grape#name:tom;sam;dim;ham" > ,"class1:instance1[~]#class2:instance2[;]") > return: {"class1":"fruit", > instance1:['apple','orange','pear','grape'], > "class2":"name", > "instance2":['tom','sam','dim','ham'] > } Your best bets are simpleparse (http://simpleparse.sourceforge.net/) or ply (http://www.dabeaz.com/ply/ply.html). Both have a little learning curve but are well worth the time investment if you will be doing things like you describe. James From plahey at alumni.caltech.edu Sun Mar 5 12:43:43 2006 From: plahey at alumni.caltech.edu (plahey at alumni.caltech.edu) Date: 5 Mar 2006 09:43:43 -0800 Subject: raw strings and \ In-Reply-To: <1hbpy3y.23h9u0zn7y7zN%aleaxit@yahoo.com> References: <1141548565.145199.145910@e56g2000cwe.googlegroups.com> <1141576051.081203.318010@e56g2000cwe.googlegroups.com> <1hbpy3y.23h9u0zn7y7zN%aleaxit@yahoo.com> Message-ID: <1141580623.066639.51160@u72g2000cwu.googlegroups.com> Hi Alex, thanks for the reply. I can see that there is a choice that needed to be made. Before I was aware of the \ issue I just used (yes it has come up, but the example is at work) triple quotes to work around the embedded quote issue: x=r'''It's like this "c:\blah\" ok?''' print x It's like this "c:\blah\" ok? Am I missing something? I guess my point is that it is quite surprising that r'\' is not a legal way to represent a backslash. I look for consistency in the tools that I work with and this except-for-the-last-character exception is annoying (I admit it might be a silly use-case but consistency is consistency). Again, thanks for taking the time to reply. Now get back to work on your new Nutshell book :-) From nick.smallbone at gmail.com Thu Mar 9 19:34:35 2006 From: nick.smallbone at gmail.com (Nick Smallbone) Date: 9 Mar 2006 16:34:35 -0800 Subject: About IDLE? In-Reply-To: <2i3Qf.3304$Bj7.629@newsread2.news.pas.earthlink.net> References: <2i3Qf.3304$Bj7.629@newsread2.news.pas.earthlink.net> Message-ID: <1141950875.398548.75180@p10g2000cwp.googlegroups.com> Dr. Pastor wrote: > Any reply? > ahem. three replies, when i counted: http://groups.google.com/group/comp.lang.python/browse_frm/thread/ab0c8455251e616c/ From g.brandl-nospam at gmx.net Tue Mar 21 18:36:08 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 22 Mar 2006 00:36:08 +0100 Subject: ** Operator In-Reply-To: References: <1142833145.976550.104830@v46g2000cwv.googlegroups.com><1142833540.860154.137040@u72g2000cwu.googlegroups.com><1hcgw5p.1ufznwe1lxeagfN%aleaxit@yahoo.com><1142864492.645457.291240@j33g2000cwa.googlegroups.com> <441ed65c$1_3@newspeer2.tds.net> Message-ID: <48bgv8Finqp2U1@individual.net> Terry Reedy wrote: >>> ... which was promptly rejected. >> >> ... but now it has been checked in by somebody else anyway. The Python >> gods sometimes move in mysterious ways ;-) > > The tracker item reviewers are people, including me, with different > knowledge, viewpoints and experiences, who sometimes disagree. Had I seen the tracker item and/or read this thread to the end before I made that checkin, I probably wouldn't have made it... ;) Georg From http Tue Mar 7 21:17:31 2006 From: http (Paul Rubin) Date: 07 Mar 2006 18:17:31 -0800 Subject: generators shared among threads References: <1141497912.606351.232440@j33g2000cwa.googlegroups.com> <1hbo9a3.1pfr3uy160d79iN%aleaxit@yahoo.com> <7xzmk2nhu9.fsf@ruckus.brouhaha.com> <1141779301.471629.157640@e56g2000cwe.googlegroups.com> Message-ID: <7xmzg18ytg.fsf@ruckus.brouhaha.com> jess.austin at gmail.com writes: > The main problem with this is that the yield leaves the lock locked. > If any other thread wants to read the generator it will block. Ouch, good catch. Do you see a good fix other than try/finally? Is there a classical way to do it with coroutines and semaphores? From onurb at xiludom.gro Wed Mar 29 08:25:04 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 29 Mar 2006 15:25:04 +0200 Subject: Python plug-in In-Reply-To: <44299fc5$0$1148$7a628cd7@news.club-internet.fr> References: <44299fc5$0$1148$7a628cd7@news.club-internet.fr> Message-ID: <442a8af0$0$1104$626a54ce@news.free.fr> toto wrote: > Hi, > > I'm trying to find some howto, tutorial in order to create a python program > that will allow plug-in programming. I've found various tutos on how to > write a plug-in for soft A or soft B but none telling me how to do it in my > own programs. Do you have any bookmarks ?? Trac and MoinMoin have a plugin system IIRC. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From nospam at nospam.com Tue Mar 7 13:33:25 2006 From: nospam at nospam.com (3c273) Date: Tue, 7 Mar 2006 10:33:25 -0800 Subject: Opening files without closing them References: <1141598002.402189.275520@i40g2000cwc.googlegroups.com> <7xu0abgr12.fsf@ruckus.brouhaha.com> Message-ID: "Robert Kern" wrote in message news:mailman.2794.1141683892.27775.python-list at python.org... > Paul Rubin wrote: > > Say that the open is inside the try block. If the file can't be > > opened, then 'open' raises an exception, 'f' doesn't get set, and then > > the 'finally' clause tries to close f. f might have been previously > > bound to some other file (which still has other handles alive) and so > > the wrong file gets closed. > > And even if 'f' wasn't bound to anything, you will get a NameError instead of > the exception that you're really interested in seeing. Thanks to both of you. So in order to be thorough, should I be doing: try: f=open('file') except: IOError: print 'doesn't exist' so_something_else_instead() try: contents = f.read() finally: f.close() Thanks again. Louis From michele.simionato at gmail.com Fri Mar 24 08:18:20 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 24 Mar 2006 05:18:20 -0800 Subject: Strange metaclass behaviour In-Reply-To: <1143203404.329141.194770@z34g2000cwc.googlegroups.com> References: <1143127358.820526.259930@i40g2000cwc.googlegroups.com> <1143138624.25186@news.aic.at> <1143188732.510491.233900@t31g2000cwb.googlegroups.com> <1143203404.329141.194770@z34g2000cwc.googlegroups.com> Message-ID: <1143206300.642179.278050@e56g2000cwe.googlegroups.com> Ziga Seilnacht wrote: > >>> def in_class_statement2(): > ... frame = sys._getframe(1) > ... return '__module__' in frame.f_locals and not \ > ... '__module__' in frame.f_code.co_varnames On second thought, to break this check is less easy than I expected, so maybe it is reliable enough. BTW, if you are interested, you can check the original code in zope.interface.advice. From henrik at wollesens.dk Thu Mar 30 08:25:08 2006 From: henrik at wollesens.dk (henrik at wollesens.dk) Date: 30 Mar 2006 05:25:08 -0800 Subject: Countdown from 2 minutes - how? Message-ID: <1143725108.307128.16110@v46g2000cwv.googlegroups.com> Hi. Can anyone tell me the python code for a simple countdown from eg. 2.00 minutes. It should be printet out to the screen. When it is finished it should write "Time is up" Hope you can help. Henrik From fredrik at pythonware.com Tue Mar 21 02:47:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 21 Mar 2006 08:47:43 +0100 Subject: New-style Python icons References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> Message-ID: and-google at doxdesk.com wrote: > I've taken the opportunity to knock up some icons using it, finally > banishing the poor old standard-VGA-palette snake from my desktop. If > you like, you can grab them from: > > http://www.doxdesk.com/img/software/py/icons.zip > > in .ICO format for Windows - containing all resolutions/depths up to > and including Windows Vista's crazy new enormo-icons. Also contains the > vector graphics source file in Xara format. could you perhaps add an SVG version ? From adelagon at gmail.com Thu Mar 9 13:08:19 2006 From: adelagon at gmail.com (Alvin A. Delagon) Date: Thu, 09 Mar 2006 18:08:19 +0000 Subject: Threading.Lock() question Message-ID: <44106F13.7000803@gmail.com> @ Dennis Thanks for the quick heads up! You're right! I noticed the bug on my script just after sending out my question. Yes, I'm using MySQLdb but I did a wrapper for it to further simplify my script that why the sample script I wrote is a little bit different. Thanks again! Python rules!!! ^_^ From michel.salim at gmail.com Fri Mar 3 14:02:02 2006 From: michel.salim at gmail.com (Michel Salim) Date: 3 Mar 2006 11:02:02 -0800 Subject: Tail Call Optimization as a Decorator References: <1140981639.315995.34860@i39g2000cwa.googlegroups.com> Message-ID: <1141412522.302535.151580@t39g2000cwt.googlegroups.com> Neat stuff! I commented on the ActiveState post, but for completeness, I modified your code to support mutual recursions, and used jorend's isTailCall() to make it safe to call an optimized function in a non-tail-call context. http://the-dubois-papers.blogspot.com/2006/03/python-tail-call-decorator.html From iainking at gmail.com Fri Mar 3 07:29:27 2006 From: iainking at gmail.com (Iain King) Date: 3 Mar 2006 04:29:27 -0800 Subject: object's list index In-Reply-To: References: Message-ID: <1141388967.849854.239830@z34g2000cwc.googlegroups.com> William Meyer wrote: > hi, > > I need to get the index of an object in a list. I know that no two objects > in the list are the same, but objects might evaluate as equal. for example > > list = [obj1, obj2, obj3, obj4, obj5] > for object in list: > objectIndex = list.index(object) > print objectIndex > > prints 0, 1, 2, 3, 2 instead of 0, 1, 2, 3, 4 because obj3 == obj5. I could loop > through the list a second time comparing id()'s > > for object in list: > objectIndex = 0 > for i in list: > if id(object) == id(i): > break > objectIndex += 1 > print objectIndex > > but that seems like a real ugly pain. Somewhere, someplace python is keeping > track of the current index in list, does anyone know how to access it? Or have > any other suggestions? Um, one of us is being really really dense today :) I hope it's not me... what's wrong with: i = 0 for object in list: objectIndex = i print objectIndex i += 1 Iain From robert.kern at gmail.com Mon Mar 27 16:26:29 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 27 Mar 2006 15:26:29 -0600 Subject: Where does Python look for libraries? In-Reply-To: <442851CD.8070604@python.org.ve> References: <442851CD.8070604@python.org.ve> Message-ID: Jesus Rivero - (Neurogeek) wrote: > Python has sys.path > If you want to add dirs into your PYTHONPATH add them to sys.path The OP seems to be asking about C libraries dynamically linked to extension modules, not Python libraries. > ACB wrote: >>>I have been trying to get the gdmodule installed and have run into >>>an issue. When I import gd I get the following error. >>> >>> >>>>>>import gd >>> >>>Traceback (most recent call last): File "", line 1, in ? >>>File "/usr/local/lib/python2.3/site-packages/gd.py", line 10, in ? >>>import _gd ImportError: /usr/local/lib/libgd.so.2: Undefined symbol >>>"libiconv_open" >>> >>>But, when I run nm libiconv.so in the directory with the iconv >>>library I get an entry like this 00011fe0 T libiconv_open >>> >>>so I know the functionality is there. So, my question. Does >>>python have a way to add search directories for locating libraries? No. You will have to read your OS's documentation on how to make sure libiconv.so is in a location your dynamic linker will look for shared libraries. If you are on Linux, then probably $ man ld.so will tell you the appropriate information. -- Robert Kern robert.kern at gmail.com "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 detlev at die-offenbachs.de Wed Mar 29 12:45:27 2006 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Wed, 29 Mar 2006 19:45:27 +0200 Subject: Free Python IDE ? References: <1143653654.234759.133800@j33g2000cwa.googlegroups.com> Message-ID: Ernesto wrote: > I'm looking for a tool that I can use to "step through" python software > (debugging environment). Is there a good FREE one (or one which is > excellent and moderately priced ) ? Try eric3 (http://www.die-offenbachs.de/detlev/eric3.html). It is a Python IDE with batteries included and it is free. Detlev -- Detlev Offenbach detlev at die-offenbachs.de From http Thu Mar 2 21:47:23 2006 From: http (Paul Rubin) Date: 02 Mar 2006 18:47:23 -0800 Subject: do design patterns still apply with Python? References: <8SINf.1718$No6.40137@news.tufts.edu> <1141333305.284973.54620@z34g2000cwc.googlegroups.com> <1141340833.768460.193010@j33g2000cwa.googlegroups.com> Message-ID: <7xmzg86y84.fsf@ruckus.brouhaha.com> "ajones" writes: > Design patterns are kind of like sarcasm: hard to use well, not always > appropriate, and disgustingly bad when applied to problems they are not > meant to solve. +1 QOTW From exarkun at divmod.com Sun Mar 19 21:39:21 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 19 Mar 2006 21:39:21 -0500 Subject: whats your favourite object relational mapper? In-Reply-To: <1142819539.741782.189420@v46g2000cwv.googlegroups.com> Message-ID: <20060320023921.22481.466067215.divmod.quotient.2741@ohm> On 19 Mar 2006 17:52:19 -0800, Serge Orlov wrote: >Flavio wrote: >> With so many object relational mappers out there, I wonder which one is >> the preferred tool among the Pythonists... is there a favourite? >> >> Sqlobject, PyDO, SQLAlchemy, dejavu, etc... > >Google results: >Sqlobject ORM: about 17,100 >PyDO ORM: 469 >SQLAlchemy ORM: 571 >dejavu ORM: 659 > axiom orm: about 21,500 Although "axiom" is not exactly unique. How about: divmod axiom: 34,500 Huh. Jean-Paul From deets at nospam.web.de Sat Mar 25 12:12:20 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 25 Mar 2006 18:12:20 +0100 Subject: check object being a compiled regular expression In-Reply-To: <44256892$0$14646$ba620e4c@news.skynet.be> References: <44256892$0$14646$ba620e4c@news.skynet.be> Message-ID: <48lbvkFkaqmvU1@uni-berlin.de> Helmut Jarausch schrieb: > Hi, > sorry, this seems to be a FAQ but I couldn't find anything > > I need to check if an object is a compiled regular expression > > Say > import re > RX= re.compile('^something') > > how to test > > "if RX is a compiled regular expression" > > type(RX) says > > > but > > if isinstance(RX,_sre.SRE_Pattern) > and > if isinstance(RX,re._sre.SRE_Pattern) > both fail. > > Many thanks for a hint, Just invoke type on a compiled expression and store that: 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. Welcome to rlcompleter2 0.96 for nice experiences hit multiple times >>> import re >>> re_type = type(re.compile("foo")) >>> isinstance(re.compile("bar"), re_type) True >>> Diez From arne at citde.net Wed Mar 22 11:09:33 2006 From: arne at citde.net (Arne Ludwig) Date: 22 Mar 2006 08:09:33 -0800 Subject: Windows getting local ip address In-Reply-To: References: <1143041866.826115.242680@i39g2000cwa.googlegroups.com> Message-ID: <1143043773.821573.268240@t31g2000cwb.googlegroups.com> The second solution can give really weird results though, e.g. on my Linux system I get: >>> gethostbyaddr(gethostname()) ('linux.site', ['linux'], ['127.0.0.2']) A more flexible but potentially unportable way would be: >>> import socket >>> import fcntl >>> import struct >>> >>> def get_ip_address(ifname): ... s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ... return socket.inet_ntoa(fcntl.ioctl( ... s.fileno(), ... 0x8915, # SIOCGIFADDR ... struct.pack('256s', ifname[:15]) ... )[20:24]) ... >>> get_ip_address('eth0') '192.168.0.174' From scott.catalina.ctr at scott.af.mil Mon Mar 6 09:44:36 2006 From: scott.catalina.ctr at scott.af.mil (Catalina Scott A Contr AFCA/EVEO) Date: Mon, 6 Mar 2006 08:44:36 -0600 Subject: help with loops Message-ID: <56BF0C633F594948B90E97636666DDF7A04C64@AMCW3VN503.amc.ds.af.mil> Hello, I am not having luck writing code to do what I want and could use a hand. I have two files and I want to pull out lines from file 2 if certain conditions are found if file 1. for line in readfile1: list1 = line.split(',') for line in readfile2: list2 = line.split(',') if list1[3] == list2[6] and list1[4] == list2[8]: print line This code only compares the last line of readfile1. I want it to check all lines. But I do not know how to construct the loop. Thanks in advance, Scott -------------- next part -------------- An HTML attachment was scrubbed... URL: From prettyboy988-google at yahoo.com Fri Mar 10 17:01:04 2006 From: prettyboy988-google at yahoo.com (P Boy) Date: 10 Mar 2006 14:01:04 -0800 Subject: Python and C In-Reply-To: <1142001002.398147.199140@j52g2000cwj.googlegroups.com> References: <1142001002.398147.199140@j52g2000cwj.googlegroups.com> Message-ID: <1142028064.100012.256170@v46g2000cwv.googlegroups.com> I have written some C extension before but it was pretty tedious. I have recently found another approach by using ctypes (http://starship.python.net/crew/theller/ctypes/). Which you develop your C module in dynamic library (DLL in Windows world), the from Python, you can call the C functions in the DLL using ctypes. I have a library from Microsoft, ewfapi.dll, ewfapi.lib (not required), and ewfapi.h (from msdn.com) which I want to program the EWF capability in Windows XP Embedded. I was thinking about writing a Python C extension for it, but using ctypes is much easier. I only need to redefine some data structures from the header file, and not worry about common C tasks such as memory management, reference counting, etc. I have some sample usage in Python shown below, which I can interactively control the EWF feature using Python shell (in an XP embedded machine). # ewf.py import ctypes import string # These are the functions from the EWF API ##EwfMgrGetDriveLetterFromVolumeName(volumeName) ## ##EwfMgrVolumeNameListIsEmpty(volumeEntry) ## ##EwfMgrVolumeNameEntryPop(volumeEntry) ## ##EwfMgrVolumeNameListDelete ## ##EwfMgrOpenProtected ## ##EwfMgrClose = _ewfapiPy.EwfMgrClose ## ##EwfMgrClearCommand = _ewfapiPy.EwfMgrClearCommand ## ##EwfMgrSetPersistentData = _ewfapiPy.EwfMgrSetPersistentData ## ##EwfMgrGetPersistentData = _ewfapiPy.EwfMgrGetPersistentData ## ##EwfMgrCheckpoint = _ewfapiPy.EwfMgrCheckpoint ## ##EwfMgrRestore = _ewfapiPy.EwfMgrRestore ## ##EwfMgrDisable = _ewfapiPy.EwfMgrDisable ## ##EwfMgrEnable = _ewfapiPy.EwfMgrEnable ## ##EwfMgrCommit = _ewfapiPy.EwfMgrCommit ## ##EwfMgrCommitAndDisableLive = _ewfapiPy.EwfMgrCommitAndDisableLive ## ##EwfMgrCommitFile = _ewfapiPy.EwfMgrCommitFile ## ##EwfMgrSetLevel = _ewfapiPy.EwfMgrSetLevel ## ##EwfMgrGetProtectedVolumeConfig = _ewfapiPy.EwfMgrGetProtectedVolumeConfig ## ##EwfMgrGetProtectedVolumeList = _ewfapiPy.EwfMgrGetProtectedVolumeList ## ##EwfMgrOpenOverlayStore = _ewfapiPy.EwfMgrOpenOverlayStore ## ##EwfMgrGetOverlayStoreConfig = _ewfapiPy.EwfMgrGetOverlayStoreConfig ## ##EwfMgrRegisterLowSpaceNotification = _ewfapiPy.EwfMgrRegisterLowSpaceNotification # Short handle to the API ewfapi = ctypes.windll.ewfapi # Data structure from EWFAPI.h translated into Python # Map these enumerations to string EWF_CMD = { 0 : 'NO Command', 1 : 'Enable', 2 : 'Disable', 3 : 'Set Level', 4 : 'Commit', } EWF_STATE = { 0 : 'Enabled', 1 : 'Disabled', } EWF_TYPE = { 0 : 'Disk', 1 : 'RAM', 2 : 'RAM Reg', } # Forward Declaration pVolumeNameEntry = ctypes.POINTER('VolumeNameEntry') # Structure of a linked-list class VolumeNameEntry(ctypes.Structure): _fields_ = [('Next', ctypes.POINTER(pVolumeNameEntry)), ('Name', ctypes.c_wchar * 256), ] # Set the pointer to the structure ctypes.SetPointerType(pVolumeNameEntry, VolumeNameEntry) # Volume descriptor class VolumeDesc(ctypes.Structure): _fields_ = [('DeviceName', ctypes.c_wchar * 256), ('VolumeID', ctypes.c_ubyte * 16), ] pVolumeDesc = ctypes.POINTER(VolumeDesc) # Overlay configuration class OverlayStoreConfig(ctypes.Structure): _fields_ = [('FormatVersion', ctypes.c_ulong), ('VolumeSize', ctypes.c_longlong), ('NumSegments', ctypes.c_ulong), ('FreeSegments', ctypes.c_ulong), ('SegmentSize', ctypes.c_ulong), ('MaxVolumes', ctypes.c_ulong), ('NumVolumes', ctypes.c_ulong), ('MaxLevels', ctypes.c_ushort), ('VolumeDescArray', pVolumeDesc), ] pOverlayStoreConfig = ctypes.POINTER(OverlayStoreConfig) class Command(ctypes.Structure): _fields_ = [('Command', ctypes.c_int), ('Param1', ctypes.c_ulong), ('Param2', ctypes.c_ulong), ] pCommand = ctypes.POINTER(Command) class FileTime(ctypes.Structure): _fields_ = [('LowDateTime', ctypes.c_ulong), ('HighDateTime', ctypes.c_ulong), ] pFileTime = ctypes.POINTER(FileTime) class LevelDesc(ctypes.Structure): _fields_ = [('LevelName', ctypes.c_wchar * 64), ('LevelEndTime', FileTime), ('LevelDataSize', ctypes.c_longlong), ] pLevelDesc = ctypes.POINTER(LevelDesc) class VolumeConfig(ctypes.Structure): _fields_ = [('Type', ctypes.c_int), ('State', ctypes.c_int), ('BootCommand', Command), ('PersistentData', ctypes.c_ubyte * 32), ('MaxLevels', ctypes.c_ushort), ('ClumpSize', ctypes.c_ulong), ('CurrentLevel', ctypes.c_ushort), ('DiskMap_RamDataSize', ctypes.c_longlong), ('DiskDataSize', ctypes.c_longlong), ('MemMapSize', ctypes.c_ulong), ('VolumeDesc', VolumeDesc), ('LevelDescArray', pLevelDesc), ] def formatUnsigned(u): return '%02X' % u def unsignedArrayToHex(array): return string.join(map(formatUnsigned, array)).replace(' ','') def displayVolumeConfiguration(config, drive): config_type = EWF_TYPE[config.Type] print 'Type : %s' % config_type print 'State : %s' % EWF_STATE[config.State] print 'Boot Cmd : %s' % EWF_CMD[config.BootCommand.Command] print 'Param 1 : %u' % config.BootCommand.Param1 print 'Param 2 : %u' % config.BootCommand.Param2 print 'Persistent Data: %s' % unsignedArrayToHex(config.PersistentData) print print 'Maximum Levels : %u' % config.MaxLevels print 'Clump Size : %u Bytes' % config.ClumpSize print 'Current Level : %u' % config.CurrentLevel if config_type == 'Disk': print 'Disk Map Size : %u Bytes' % config.DiskMap_RamDataSize print 'Disk Data Size : %u Bytes' % config.DiskDataSize else: print 'RAM Data Size : %u Bytes' % config.DiskMap_RamDataSize print 'Memory Map Size : %u Bytes' % config.MemMapSize print 'Device Name : %s' % config.VolumeDesc.DeviceName print 'Volume ID : %s' % unsignedArrayToHex(config.VolumeDesc.VolumeID) print 'Drive : %s' % drive def information(): # Get the pointer and convert to linked-list node volume_list = VolumeNameEntry.from_address(ewfapi.EwfMgrGetProtectedVolumeList()) while 1: drive = chr(ewfapi.EwfMgrGetDriveLetterFromVolumeName(volume_list.Name)) print '%s: = %s' % (drive, volume_list.Name) handle = ewfapi.EwfMgrOpenProtected(volume_list.Name) config = VolumeConfig.from_address(ewfapi.EwfMgrGetProtectedVolumeConfig(handle)) displayVolumeConfiguration(config, drive) if ewfapi.EwfMgrVolumeNameListIsEmpty(ctypes.c_void_p.from_address(ctypes.addr?essof(volume_list))): break if __name__ == "__main__ ": print 'Running' information() From steven.bethard at gmail.com Sun Mar 26 12:34:16 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 26 Mar 2006 10:34:16 -0700 Subject: maximum() efficency In-Reply-To: References: Message-ID: Steve R. Hastings wrote: > I was looking at a Python function to find the maximum from a list. > The original was more complicated; I simplified it. The built-in max() > function can replace the simplified example, but not the original. What's the original? Are you sure max can't solve it with an appropriate decorate-sort-undecorate (DSU) or the key= argument coming in Python 2.5? STeVe From abhinavduggal at gmail.com Mon Mar 27 06:03:17 2006 From: abhinavduggal at gmail.com (abhinav) Date: 27 Mar 2006 03:03:17 -0800 Subject: Python multithreading problem In-Reply-To: <1143415130.057167.196190@e56g2000cwe.googlegroups.com> References: <1143404603.763070.319690@z34g2000cwc.googlegroups.com> <1143415130.057167.196190@e56g2000cwe.googlegroups.com> Message-ID: <1143457396.976557.103240@u72g2000cwu.googlegroups.com> thanks guys.I solved the problem by moving self.stdmutex.acquire() before if c<5: From rurpy at yahoo.com Fri Mar 17 23:56:21 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 17 Mar 2006 20:56:21 -0800 Subject: Python equivalent of Perl-ISAPI? Message-ID: <1142657781.197131.222440@g10g2000cwb.googlegroups.com> Is there an effcient way (more so than cgi) of using Python with Microsoft IIS? Something equivalent to Perl-ISAPI? From scott.daniels at acm.org Sun Mar 5 11:34:15 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 05 Mar 2006 08:34:15 -0800 Subject: lists: += vs. .append() & oddness with scope of variables In-Reply-To: References: Message-ID: <440b111f$1@nntp0.pdx.net> Duncan Booth wrote: > Sandro Dentella wrote: > >> I'd like to understand why += operator raises an error while .append() >> does not. My wild guess is the parses treats them differently but I >> cannot understand why this depends on scope of the variables (global >> or class variables): >.... > > Any assignment to a variable within a function means that the name to which > you are assigning is regarded as a local variable (unless you use the > 'global' statement to override that). += is a form of assignment, calling > the append method is not an assignment. > > The solution here is simply to use 'global a' to tell the compiler that you > meant to assign the the global variable rather than creating a new local > variable. As Duncan knows but forgot to mention, eric.append(spam) doesn't write the variable eric, it simply manipulates the object that eric names. -- -Scott David Daniels scott.daniels at acm.org From kent at kentsjohnson.com Wed Mar 22 13:17:06 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 22 Mar 2006 13:17:06 -0500 Subject: string.upto() and string.from() In-Reply-To: <1143046848.975294.287350@i40g2000cwc.googlegroups.com> References: <1143038492.748562.267150@i40g2000cwc.googlegroups.com> <442173ff$1_3@newspeer2.tds.net> <1143046848.975294.287350@i40g2000cwc.googlegroups.com> Message-ID: <44218f8c$1_1@newspeer2.tds.net> ikshefem at gmail.com wrote: > Sure, you're right I forgot about rsplit ! > I guess the negative indexes & al could be done with > > sep.join(xyz.split(sep)[:index]) For index=-1 use xyz.rsplit(sep, 1)[0] Kent From irvine.david at gmail.com Mon Mar 20 07:01:59 2006 From: irvine.david at gmail.com (dirvine) Date: 20 Mar 2006 04:01:59 -0800 Subject: Pycrypto - active ?? In-Reply-To: <7xslpdl7yg.fsf@ruckus.brouhaha.com> References: <1142804398.710230.117640@j33g2000cwa.googlegroups.com> <1142807299.141313.306980@i40g2000cwc.googlegroups.com> <1142841321.980154.320340@u72g2000cwu.googlegroups.com> <7xslpdl7yg.fsf@ruckus.brouhaha.com> Message-ID: <1142856119.461122.293150@i40g2000cwc.googlegroups.com> Thanks Paul I will check this out. Perhaps theres a case for pycrypto to be revamped and perhaps a new python cryptographic page to be created mentioning all these projects. I have foudn it a bit difficult to find info on this area. Mny thanks for this though. From webraviteja at gmail.com Fri Mar 31 19:29:45 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 31 Mar 2006 16:29:45 -0800 Subject: Find similar images using python In-Reply-To: <1143642554.075130.150990@e56g2000cwe.googlegroups.com> References: <1143637570.842988.44030@z34g2000cwc.googlegroups.com> <442a95b5$1@nntp0.pdx.net> <1143642554.075130.150990@e56g2000cwe.googlegroups.com> Message-ID: <1143851385.669942.109260@j33g2000cwa.googlegroups.com> Finding similar images is not at all a trivial task. Entire PhD dissertations have been committed to it. The solutions are still very unreliable as of yet. If you want to find more, you can read the research out of the ongoing Image CLEF track. I worked with them briefly a couple of years ago in context of medical images. http://ir.shef.ac.uk/imageclef/ From justin.frost at gmail.com Fri Mar 10 13:05:55 2006 From: justin.frost at gmail.com (MakaMaka) Date: 10 Mar 2006 10:05:55 -0800 Subject: creating variable in root namespace from module In-Reply-To: References: <1141976796.594066.229210@e56g2000cwe.googlegroups.com> <1142009812.786850.218860@z34g2000cwc.googlegroups.com> Message-ID: <1142013955.214142.124160@e56g2000cwe.googlegroups.com> Steve, I think I actually need to get the caller's local namespace. How do I do that using sys? I read the documentation and can't find anything specific. For example, if I have module A and it imports module B, I want module B to add variables to A's global namespace. Python has to store this info somewhere in order to return to A after a function is run in B. I can certainly look at it the Komodo debugger call stack. Thanks, -Justin From alainpoint at yahoo.fr Mon Mar 13 12:51:11 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 13 Mar 2006 09:51:11 -0800 Subject: Is this possible in Python? In-Reply-To: <1142242308.448726.78760@i40g2000cwc.googlegroups.com> References: <1142238871.199749.243470@p10g2000cwp.googlegroups.com> <1142242308.448726.78760@i40g2000cwc.googlegroups.com> Message-ID: <1142271462.640996.198090@i40g2000cwc.googlegroups.com> Kay Schluehr wrote: > Storing arguments away before they are evaluated doesn't work in > Python. You have to hack the compiler in order to access the parsetree. > You might take a look at the compiler package of the standard library > that enables access to ASTs. Thus you could define lazy evaluation and > just-in-time compilation of some particular ASTs. I do not recommend > doing this for real purposes, but it is a good excercise and sooner or > later you become an expert yourself :) > > Kay I made some investigation and reached a (partial) solution to my problem. It is inspired from a cookbook recipe but it only works for generator expressions.: import tokenize import token def magic_function(s): cursor = None # to be set to the cursor of the connection return_type = object # can be set to dict or list _iterating = False # used in next() readline = open(s.gi_frame.f_code.co_filename).readline first_line = s.gi_frame.f_code.co_firstlineno flag = False source = '' # the source code for t in tokenize.generate_tokens(open(s.gi_frame.f_code.co_filename).readline): # check all tokens until the last parenthesis is closed t_type,t_string,(r_start,c_start),(r_end,c_end),line = t t_name = token.tok_name[t_type] if r_start == first_line: if t_name == 'NAME' and t_string=="magic_function": flag = True res = t_string start = 0 # number of parenthesis continue if flag: source += ' '+t_string if t_name == 'OP': if t_string=='(': start += 1 elif t_string == ')': start -= 1 if start == 0: break return source[2:-2] assert magic_function(i+2 for i in [1,2])=="i+2 for i in [1,2]" or print magic_function(i+2 for i in [1,2]) A general solution is possible and i am sure there are people around that will provide such a solution Alain From jbellis at gmail.com Tue Mar 28 12:10:34 2006 From: jbellis at gmail.com (Jonathan Ellis) Date: 28 Mar 2006 09:10:34 -0800 Subject: Threads and sys.excepthook In-Reply-To: References: Message-ID: <1143565834.312655.95030@g10g2000cwb.googlegroups.com> Jesus Rivero - (Neurogeek) wrote: > Original exception was: > Unhandled exception in thread started by > Error in sys.excepthook: > > Original exception was: > > And if put a time.sleep(1) after the thread.start_new(test, > (name,)) #(1) part, then it does it all perfectly. Looks like the interpreter is shutting down before all the exception processing finishes. -Jonathan From email at christoph-haas.de Tue Mar 21 17:06:33 2006 From: email at christoph-haas.de (Christoph Haas) Date: Tue, 21 Mar 2006 23:06:33 +0100 Subject: nested for loops In-Reply-To: References: Message-ID: <20060321220633.GA6423@aldi.workaround.org> On Tue, Mar 21, 2006 at 09:54:21PM +0000, John Salerno wrote: > Can someone tell me why 'n' in this example isn't 2? > > >>> for n in range(2, 10): > for x in range(2, n): > print 'x =', x, 'n =', n > > > x = 2 n = 3 Assume n=2. Then the first inner loop will run in a range(2,2) which is an empty list. So nothing will happen. Next outer loop: n=3... Actually n becomes 2. But you don't do anything with it. :) Christoph -- ~ ~ ".signature" [Modified] 1 line --100%-- 1,48 All From cito at online.de Wed Mar 1 13:57:35 2006 From: cito at online.de (Christoph Zwerschke) Date: Wed, 01 Mar 2006 19:57:35 +0100 Subject: ihooks and Python eggs Message-ID: Is it a known problem that ihooks is incompatible with Python eggs? When I do the following: import ihooks ihooks.install(ihooks.ModuleImporter()) then I cannot import any Python egg afterwards. Can there be anything done about this? -- Christoph From paddy3118 at netscape.net Sun Mar 5 02:39:39 2006 From: paddy3118 at netscape.net (Paddy) Date: 4 Mar 2006 23:39:39 -0800 Subject: XP rich text cut-n-paste In-Reply-To: References: <1141501151.073307.281850@u72g2000cwu.googlegroups.com> Message-ID: <1141544379.024095.10840@v46g2000cwv.googlegroups.com> Thanks Chris, Scintilla does indeed have the feature, and googling for the term "copy as RTF" lead me to http://www.pnotepad.org/ which also has the feature. Now I will have to ask for that feature request as I wuld also like colourized shell input oo! (Hmm, must get that credit card authorized so I can make a donation). - Paddy. From Serge.Orlov at gmail.com Thu Mar 16 21:34:06 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 16 Mar 2006 18:34:06 -0800 Subject: accessing a USB HID In-Reply-To: <1142557118.268666.108770@e56g2000cwe.googlegroups.com> References: <1142557118.268666.108770@e56g2000cwe.googlegroups.com> Message-ID: <1142562846.796988.277080@j33g2000cwa.googlegroups.com> jodansmif at gmail.com wrote: > I've been teaching myself Python as part of my senior design project at > university. > > The obstacle our group currently faces is communicating with a > microcontroller (ACS USB Servo II) that appears in Windows as a USD > HID. Unfortunately, the vendor's sample code is in Visual Basic and > Visual C++ which none of our group members have any experience using. > > My hope is that someone has experience with this type of problem and > can point me to some reference material. At this point I'm a bit lost > in the morass of USB terminology. > > While I'm at it... if anyone knows of a better way to approach this > problem (serial or parallel microcontroller) or another language with > better tools, I'd appreciate that as well. We're just trying to turn > several motors on and off while polling some photodiodes and all this > HID business seems like unnessary overkill. After cursory look at the device home page it appears the vendor is providing an Active X control. So it looks like you will need to learn client side COM programming no matter what language you choose. For Python you will need win32 extensions: http://starship.python.net/crew/mhammond/win32/Downloads.html or you can use ActivePython distribution that comes integrated with it. Don't be scared by USB HID, it's just a mandatory classification of the device under Windows, you don't need to deal with it. Python and COM don't look scary: http://www.python.org/windows/win32com/QuickStartClientCom.html -- Serge. From trepca at gmail.com Fri Mar 10 09:33:57 2006 From: trepca at gmail.com (Sebastjan Trepca) Date: Fri, 10 Mar 2006 15:33:57 +0100 Subject: File Permissions In-Reply-To: <1142000418.480825.247970@v46g2000cwv.googlegroups.com> References: <1142000418.480825.247970@v46g2000cwv.googlegroups.com> Message-ID: Those constants are in stat module so add "import stat" before the program. On 10 Mar 2006 06:20:18 -0800, VJ wrote: > Hi All > > I need to get the user permission of a file using python. I was trying > the following code which i found on google grups > > st = os.stat(myfile) > mode = st[stat.ST_MODE] > if mode & stat.ST_IREAD: > print "readable" > if mode & stat.ST_IWRITE: > print "writable" > if mode & stat.ST_IEXEC: > print "executable" > > I am getting a error saying > > " Traceback (most recent call last): > File "./test.py", line 23, in ? > if mode & stat.ST_IREAD: > AttributeError: 'module' object has no attribute 'ST_IREAD' " > > any idea how to resolve this error ?? > > Basically i want to write into a file .If the permissions are not there > then print a error message. > How do i achive this ??? > > Thanks, > VJ > > -- > http://mail.python.org/mailman/listinfo/python-list > From johnjsal at NOSPAMgmail.com Wed Mar 29 22:11:50 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 29 Mar 2006 22:11:50 -0500 Subject: is 2.4.3 final? In-Reply-To: References: <8fDWf.1858$No6.41986@news.tufts.edu> Message-ID: <442b4d8f$0$9411$c3e8da3@news.astraweb.com> Terry Reedy wrote: > "John Salerno" wrote in message > news:8fDWf.1858$No6.41986 at news.tufts.edu... >> I just noticed on one page of the Python website that it said: >> >> "We are pleased to announce the release of Python 2.4.3 (final), a >> bugfix release of Python 2.4, on March 29, 2006." > > I believe today was the target date for this. Given that there have been > no mentions of problems either here or on py-dev, I would expect it to have > appeared. Thanks. I'll wait a few days before installing, just to be sure. From crema at bu.edu Sat Mar 18 10:24:34 2006 From: crema at bu.edu (Matt Crema) Date: Sat, 18 Mar 2006 15:24:34 GMT Subject: Linear regression in NumPy In-Reply-To: References: <1142628938.982098.239850@u72g2000cwu.googlegroups.com> <1142631926.353064.206010@p10g2000cwp.googlegroups.com> <1142639157.977175.257900@u72g2000cwu.googlegroups.com> Message-ID: Robert Kern wrote: > nikie wrote: > >>I still don't get it... >>My data looks like this: >> x = [0,1,2,3] >> y = [1,3,5,7] >>The expected output would be something like (2, 1), as y[i] = x[i]*2+1 >> >>(An image sometimes says more than 1000 words, so to make myself clear: >>this is what I want to do: >>http://www.statistics4u.info/fundstat_eng/cc_regression.html) >> >>So, how am I to fill these matrices? > > > As the docstring says, the problem it solves is min ||A*x - b||_2. In order to > get it to solve your problem, you need to cast it into this matrix form. This is > out of scope for the docstring, but most introductory statistics or linear > algebra texts will cover this. > > In [201]: x = array([0., 1, 2, 3]) > > In [202]: y = array([1., 3, 5, 7]) > > In [203]: A = ones((len(y), 2), dtype=float) > > In [204]: A[:,0] = x > > In [205]: from numpy import linalg > > In [206]: linalg.lstsq(A, y) > Out[206]: > (array([ 2., 1.]), > array([ 1.64987674e-30]), > 2, > array([ 4.10003045, 1.09075677])) > I'm new to numpy myself. The above posters are correct to say that the problem must be cast into matrix form. However, as this is such a common technique, don't most math/stats packages do it behind the scenes? For example, in Matlab or Octave I could type: polyfit(x,y,1) and I'd get the answer with shorter, more readable code. A one-liner! Is there a 'canned' routine to do it in numpy? btw, I am not advocating that one should not understand the concepts behind a 'canned' routine. If you do not understand this concept you should take 's advice and dive into a linear algebra book. It's not very difficult, and it is essential that a scientific programmer understand it. -Matt From maha.murali at gmail.com Wed Mar 1 00:31:05 2006 From: maha.murali at gmail.com (Murali) Date: 28 Feb 2006 21:31:05 -0800 Subject: Make staticmethod objects callable? In-Reply-To: References: Message-ID: <1141191065.511809.143310@p10g2000cwp.googlegroups.com> You have a text-database, each record has some "header info" and some data (text-blob). e.g. --------------------
name = "Tom" phone = "312-996-XXXX"
I last met tom in 1998. He was still single then. blah blah
name = "John" birthday = "1976-Mar-12"
I need to ask him his email when I see him next. ------------------ I use this format for a file to keep track of tit bits of information. Lets say the file has several hundred records. I know want to say generate a birthday list of people and their birthdays. Ofcourse along with that I also need the "text-blob" (because I dont want to send a birthday card to a person I dont like). In order to do this I execute a script ./filter --input=database.txt --condn='similar(name,"tom")'. The way it is implemented is simple. Have a class which has dict as its base class. For each record the text between
and
is executed with the class instance as "locals()". Now that I have a list of class instances, I just exec the condition and those instances where it evaluates True comprise the output text file. To make the user, not have to know too much python, one would like to define "functions" which can be used. For eg. similar would have the following definition @staticmethod def similar(regexp,str): return re.match("(?i)^.*%s.*$" % regexp, str) != None This way the "locals()" dictionary in the exec'ed environment has access to the function similar (if similar was callable). At the same time, I can enclose all these functions in their own name space (as static methods of a class). Right now, I declare all these "helper" functions in a different module, and "attach" the "helper" functions as keys into the dictionary. If only staticmethods were callable. For some reason (I dont recall why) the idea of converting the staticmethod into a callable still did not work, e.g. class Callable: def __init__(self,method): self.__call__ = method class Record(dict): @staticmethod def similar(regexp,string): .... self['similar'] = Callable(similar) The above did not work. The error message was still related to a staticmethod not being a callable. - Murali From fake at nospam.no Mon Mar 6 07:59:31 2006 From: fake at nospam.no (Blackbird) Date: Mon, 6 Mar 2006 13:59:31 +0100 Subject: raw strings and \ References: <1141548565.145199.145910@e56g2000cwe.googlegroups.com> <1141576051.081203.318010@e56g2000cwe.googlegroups.com> <1141580826.470715.319020@i40g2000cwc.googlegroups.com><65mdnffSMISumZHZRVnzvA@telenor.com> Message-ID: Fredrik Lundh wrote: > "Blackbird" wrote: > >> Slightly OT, but here is a crazy little program that shows the power >> of using raw strings: >> >> s=r'print "s=r\'%s\'\n%s"%(s,s)' >> print "s=r\'%s\'\n%s"%(s,s) >> >> When run, this program will print an exact copy of itself. > > I'm not sure what the raw strings brings to the table, though; it's > not like you need them to write a "self-replicating" python program: > > http://miscoranda.com/37 Great link! I wasn't aware that this was called a Quine. This one is great: _='_=%r;print _%%_';print _%_ When I hacked down the two lines, I didnt see that assigning the variable to the beginning of the program, instead of the end, essentially gets rid of literals in the actual print statement. And now I also learned about %r. From pmartin at snakecard.com Fri Mar 24 10:26:51 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 24 Mar 2006 09:26:51 -0600 Subject: image reduction script Message-ID: <%cUUf.2478$fS6.24@dukeread11> Hi, I need to write a script to reduce the resolution/color depth of an image (ex: .jpg) based on a target size. The point is for the target picture to still be "understandable" - yet I target getting down to 5K. Are there libraries out there that could help me start ? Thanks Philippe From mscottschilling at hotmail.com Fri Mar 17 17:43:22 2006 From: mscottschilling at hotmail.com (Mike Schilling) Date: Fri, 17 Mar 2006 22:43:22 GMT Subject: Xah's Edu Corner: The Concepts and Confusions of Pre-fix, In-fix, Post-fix and Fully Functional Notations References: <1142490052.127055.50130@v46g2000cwv.googlegroups.com> <1142585935.934786.115700@e56g2000cwe.googlegroups.com> Message-ID: "Roedy Green" wrote in message news:fl2m12d51dhif7o1rehnb1a59bca869eni at 4ax.com... > On 17 Mar 2006 00:58:55 -0800, "Fuzzyman" wrote, > quoted or indirectly quoted someone who said : > >>Hmmm... it displays fine via google groups. Maybe it's the reader which >>is 'non-compliant' ? > I am using Agent. You configure your database with an encoding, > which is by default the platform encoding, not UTF-8. I have just > flipped it over to UTF-8. We'll see if that makes Xah's future UTF-8 > messages more readable. Trust me, it won't help a bit. From harry.g.george at boeing.com Tue Mar 7 01:23:43 2006 From: harry.g.george at boeing.com (Harry George) Date: Tue, 7 Mar 2006 06:23:43 GMT Subject: Python and Java References: <1141686093.946407.245540@z34g2000cwc.googlegroups.com> Message-ID: "JKPeck" writes: > Suppose you have an application written in Java, and you want to enable > other applications or processes written in Python to communicate with > it, i.e., to use Python as a scripting language for the application. > On Windows you could do this with COM and various addons such as > J-Integra and Mark Hammond's libraries. > > How would you do this if you want a mechanism that is portable across > Windows, Linux, Mac, and Unix? > > Any ideas? Jython would be a natural candidate, but it is stuck at > Python 2.1 and seems to have an uncertain future. > > Thanks in advance. If you need real CPython (e.g., need add-on libraries compiled in C), then XMLRPC is a clean way to make the connection. From dthierbach at usenet.arcornews.de Fri Mar 24 05:53:46 2006 From: dthierbach at usenet.arcornews.de (Dirk Thierbach) Date: Fri, 24 Mar 2006 11:53:46 +0100 Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1143024937.827420.104100@i39g2000cwa.googlegroups.com> <20060322141400.1A00.1.NOFFLE@dthierbach.news.arcor.de> <1143110872.284192.325230@u72g2000cwu.googlegroups.com> <20060323134326.C29.0.NOFFLE@dthierbach.news.arcor.de> <1143134775.887696.5000@z34g2000cwc.googlegroups.com> <20060323212800.79D.0.NOFFLE@dthierbach.news.arcor.de> <1143193333.963153.23850@g10g2000cwb.googlegroups.com> Message-ID: <20060324105346.10AF.0.NOFFLE@dthierbach.news.arcor.de> Dinko Tenev wrote: > Dirk Thierbach wrote: [One cannot escape exponential behaviour] >> But you cannot get rid of this. Consider S = {a, b}, W = {a}. >> Then there are |S|^n result elements for n > 1, and you have to enumerate >> all of them. > Yes, but then, they are in the target set. Which is the point. If they are in the target set, you have to enumerate them. If the target set is of exponential size with respect to n, then you'll need exponential time to do that. > The point here is whether > you can generate S^n - W in Theta( n * |S^n - W| ), which may be > dramatically different from Theta( n * |S^n| ). Exactly. Hence, you use a construction that guarantees that the time needed is proportional to n*|S^n - W|: Every step you do will be enecessary to produce at least one word in the output set. Now, if |S^n - W| is still exponential, then you'll still need exponential time. But nevertheless, that's the best you can hope for. >> The automaton is: >> >> S: a -> A, b -> B >> A: a -> A >> B: b -> B > The target set is specified as S^n - W, where W is everything matching > (.*a.*b|.*b.*a). Following the construction procedure in point, this > exclusion set is matched exactly by my DFA with S initial and F final. > Then, swapping final and non-final states makes {S, A, B} final, and F > non-final. Your DFA above may be equivalent, but to me it is far from > clear exactly what algorithm would build it from the given data. Well, it's just the result from the minimazation algorithm, where my variant of the algorithm just prunes away the "stuck" state which can never produce any output. >> The point is not to "cut efficiently", the point is to enumerate >> only those words that are actually in the result set. > No, this is not the point. Naive filtering already does that. No, it doesn't. Naive filtering always will look at the complete input set, so, no matter what size |S^n - W| actually is, it will always take time in proportion to |S^n|. > By "cutting efficiently" I mean skipping over search sub-trees that > don't contain any results from the target set. Yes. Consider a different example: With the wildcard expressions W = { b*, aa*, ab* }, you'll get S^* - W = { a }. The resulting minimum FSM will just accept 'a' (start state, one final state, and the "stuck" state if you insist on it), so you skip over every other subtree when enumerating results from that automaton. And for the previous example, you'll need something like 2*n time to enumerate the output set instead of 2^n, because once you're in the "a-branch", you're producing only a's, and you're pruning away all the subtrees that start with a "b". Similarly in the "b-branch". Now clearer? - Dirk From scott.daniels at acm.org Fri Mar 31 17:48:50 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 31 Mar 2006 14:48:50 -0800 Subject: Looking for a language/framework In-Reply-To: <1143837635.846033.204910@u72g2000cwu.googlegroups.com> References: <1143559444.045808.38790@u72g2000cwu.googlegroups.com> <1hcwg6n.b3jwv5xq910tN%aleaxit@yahoo.com> <1143837635.846033.204910@u72g2000cwu.googlegroups.com> Message-ID: <442daf37$1@nntp0.pdx.net> Ravi Teja wrote: >> ... I've never seen an "object-relational mapping" (technical term for >> cruft that tries to avoid people having to learn and use SQL) which >> doesn't drive me into a murderous, foam-at-mouth rage in a very >> short time -- I *WANT* my SQL, I *LOVE* SQL, it's *WAY* more powerful >> and suitable for access to data than all those simulated "OO DB" people >> lay on top of it.... > > I for one don't have any particular love for SQL. For most purposes I > don't want to be bothered with its details. However, I am disillusioned > with ORMs. With SQL and old school database management, I had tools > such as QBEs, ERD managers to visually manage much of the details (I > perform better with pictures than text) and even if others disagree, it > worked well for me. Now with ORMs, I am back to code again. Granted, it > appears cleaner most of the time but I want to be able to not see it at > all.... But what you overlook is SQL's strength: SQL can be translated into _very_ efficient query plans w/o changing the SQL. SQL's query optimizers (more properly, de-pessimizers) give performance which can be tuned w/o touching the SQL. SQL, a language which is truly ugly, not quite standardized, and otherwise quite clunky, does manage to let you say more of what you want without specifying how to get it. This separation of result spec from query plan is what makes makes those optimizers work. The ORMs put objects on top of the DB, but in a way that either (A) violates the object model in that everything must be of the _same_ type in a table (good-bye duck-typing), or (B) gives up on most any attempt to get optimized access -- the DB becomes a persistent store, without the normal SQL feature of "our DB admin can tune this up to fly like a peregrine in full stoop." A query planner for well-insulated objects just doesn't have enough information about what it can and cannot rewrite, so it doesn't know how to estimate how much I/O one plan will cost as opposed to another. --Scott David Daniels scott.daniels at acm.org From fredrik at pythonware.com Fri Mar 24 02:15:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 24 Mar 2006 08:15:40 +0100 Subject: Terminating a subprocess '.exe' References: <1143156984.172363.246820@z34g2000cwc.googlegroups.com> Message-ID: "Ernesto" wrote: > I launch a Windows executable and wish to close it from Python. The > code is below. Normally, my program waits for rib.exe to finish, but > I'd like to be able to close it from python if possible. (I suppose if > I was going to do this, I wouldn't use .wait() ) Any ideas ? > > # Launch a program without launching a whole new cmd prompt > def launchWithoutConsole(command, args): > """Launches 'command' windowless and waits until finished""" > startupinfo = subprocess.STARTUPINFO() > startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW > return subprocess.Popen([command] + args, > startupinfo=startupinfo).wait() > > ribHandle = launchWithoutConsole("rib.exe",["recovery"]) > > # Is there a way to close "rib.exe" using ribHandle ? for 2.4 and earlier, see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462 for 2.5 (upcoming) and later, you can use either the ctypes method or the _subprocess.TerminateProcess() call. From bdesth.quelquechose at free.quelquepart.fr Sun Mar 19 17:14:31 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 19 Mar 2006 23:14:31 +0100 Subject: Counting number of each item in a list. In-Reply-To: <441d9408$0$20430$636a55ce@news.free.fr> References: <1142772092.958602.272260@e56g2000cwe.googlegroups.com> <441d58f7$0$13046$626a54ce@news.free.fr> <1142774630.426660.19970@t31g2000cwb.googlegroups.com> <441d6342$1_3@newspeer2.tds.net> <441d9408$0$20430$636a55ce@news.free.fr> Message-ID: <441dab21$0$27059$626a54ce@news.free.fr> Bruno Desthuilliers a ?crit : > Kent Johnson a ?crit : > >> sophie_newbie wrote: >> >>> Hey Bruno, >>> >>> I got an invalid syntax error when i tried using your "str_counts = >>> dict((s, str_list.count(s) for s in set(str_list))" bit of code? Maybe >>> there is a missing bracket or comma? Or maybe I need to import >>> something. >> >> >> >> It should be >> str_counts = dict((s, str_list.count(s)) for s in set(str_list)) > > > Of course, my bad :( > >> or for Python < 2.4 > > > from sets import Set as set > >> str_counts = dict([(s, str_list.count(s)) for s in set(str_list)]) >> >> Note that this solution iterates str_list once for each element of >> str_list > > > once for each *distinct* element or str_list (it iterates over the set > created from str_list). > >> - the call to count traverses the entire list to create the count. I >> expect Paul Rubin's solution will be dramatically faster for large >> lists as it only iterates str_list once. > > Yeps. But I would benchmark it before choosing one or the other solution. And of course, I was right. My solution seems to be faster than Paul's one (but slower than bearophile's), be it on small, medium or large lists. nb: A is mine, B is Paul's and C is bearophile's, and the number after is the size of the list... A100 (10000 times): 1.5801050663 B100 (10000 times): 1.87287902832 C100 (10000 times): 0.991976976395 A10000 (100 times): 1.083589077 B10000 (100 times): 1.30713891983 C10000 (100 times): 0.988032817841 A1000000 (10 times): 10.5345788002 B1000000 (10 times): 13.094493866 C1000000 (10 times): 9.67438292503 source: def countA(lst): return dict((s, lst.count(s)) for s in set(lst)) def countB(lst): counts = {} for s in lst: counts[s] = counts.get(s, 0)+1 return counts def countC(lst): counts = {} for s in lst: if s in counts: counts[s] += 1 else: counts[s] = 1 return counts def mklst(ln): from random import choice items = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx', 'yz'] return [choice(items) for i in range(ln)] lst100 = mklst(100) lst10000 = mklst(10000) lst1000000 = mklst(1000000) def run(): from timeit import Timer timers = [ ('A100', Timer('countA(lst100)', 'from __main__ import countA, lst100'), 10000), ('B100', Timer('countB(lst100)', 'from __main__ import countB, lst100'), 10000), ('C100', Timer('countC(lst100)', 'from __main__ import countC, lst100'), 10000), ('A10000', Timer('countA(lst10000)', 'from __main__ import countA, lst10000'), 100), ('B10000', Timer('countB(lst10000)', 'from __main__ import countB, lst10000'), 100), ('C10000', Timer('countC(lst10000)', 'from __main__ import countC, lst10000'), 100), ('A1000000', Timer('countA(lst1000000)', 'from __main__ import countA, lst1000000'), 10), ('B1000000', Timer('countB(lst1000000)', 'from __main__ import countB, lst1000000'), 10), ('C1000000', Timer('countC(lst1000000)', 'from __main__ import countC, lst1000000'), 10), ] for name, timer, repeat in timers: print "%s (%s times): %s" % (name, repeat, timer.timeit(repeat)) From toto at titi.de Tue Mar 28 15:42:46 2006 From: toto at titi.de (toto) Date: Tue, 28 Mar 2006 22:42:46 +0200 Subject: Python plug-in Message-ID: <44299fc5$0$1148$7a628cd7@news.club-internet.fr> Hi, I'm trying to find some howto, tutorial in order to create a python program that will allow plug-in programming. I've found various tutos on how to write a plug-in for soft A or soft B but none telling me how to do it in my own programs. Do you have any bookmarks ?? Regards, Laurent. From brianwill1 at adelphia.net Sat Mar 25 12:02:03 2006 From: brianwill1 at adelphia.net (BWill) Date: Sat, 25 Mar 2006 09:02:03 -0800 Subject: Python types In-Reply-To: <1143230541.717833.35440@e56g2000cwe.googlegroups.com> References: <1143230541.717833.35440@e56g2000cwe.googlegroups.com> Message-ID: Salvatore wrote: > Hello, > > I've read several articles where it's said that Python is weakly typed. > I'm a little surprised. All objects seem to have a perfectly defined > type > > Am i wrong? > > Regards > Aye, the other posters are right about you being right. This is just one of the great mass confusions in programming (sadly, there are a lot of them these days). From elpX at adsihqX.com Thu Mar 9 13:27:43 2006 From: elpX at adsihqX.com (Dr. Pastor) Date: Thu, 09 Mar 2006 18:27:43 GMT Subject: About IDLE? Message-ID: Installed Python 2.4.2 on Windows XP. Activated IDLE. Loaded the following into the Edit window: --- # dates are easily constructed and formatted (Tutorial 10.8) from datetime import date now = date.today() now now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") # dates support calendar arithmetic birthday = date(1985, 12, 1) age = now - birthday age.days --- When I select Run Module in the Edit window, I got only two >>> after the RESTART line. I expected to see the output of several commands! Typing in age.days do produce the number of days. Why I do not get any output? Thanks for any guidance. From justin.mailinglists at gmail.com Tue Mar 28 20:05:35 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 28 Mar 2006 17:05:35 -0800 Subject: Convert Word .doc to Acrobat .pdf files References: <1143123734.158567.97310@i39g2000cwa.googlegroups.com> <1143588342.984282.192460@e56g2000cwe.googlegroups.com> Message-ID: <1143594335.561036.309570@i39g2000cwa.googlegroups.com> "When you create a PostScript file you have to send the host fonts. Please go to the printer properties, "Adboe PDF Settings" page and turn OFF the option "Do not send fonts to Distiller". kbperry, sorry about that. go to "Printers and Faxes" go to properties for the "Adobe PDF" printer go to the "General" tab, "Printing Preferences" button "Adobe PDF Settings" tab uncheck the "Do not send fonts..." box rune, >> "'!CreatePDFAndCloseDoc" I had Adobe 6 once and recalled it had Word macros you could call. However, when I installed Adobe 7, I could not find the macros. Perhaps it has something to do with the naming. Thanks for the post. Will check it out. From lopexx at autograf.pl Mon Mar 6 07:59:52 2006 From: lopexx at autograf.pl (=?UTF-8?B?TWFyY2luIE1pZWzFvHnFhHNraQ==?=) Date: Mon, 06 Mar 2006 13:59:52 +0100 Subject: Why I chose Python over Ruby In-Reply-To: References: <1141573450.667103.8930@z34g2000cwc.googlegroups.com> Message-ID: Roy Smith wrote: > In article , > Bil Kleb wrote: > >> The parensless calls also allow one to write beautiful >> DSLs with Ruby. > > What's a DSL? Domain Specific Language. It is easy to tweak Rubys syntax and semantics into something that looks like another language designed for a specific task. lopex From ray_usenet at yahoo.com Sun Mar 19 05:39:44 2006 From: ray_usenet at yahoo.com (Ray) Date: 19 Mar 2006 02:39:44 -0800 Subject: Is Jython development active? Message-ID: <1142764784.253197.326520@i39g2000cwa.googlegroups.com> aprasad21k at gmail.com wrote: > Don't seem to see much progress in getting out a new version of Jython. > The last beta was out in March 2005. When will a final release be made? Not sure, but I've been checking jython-dev and jython-checkins once every few days (yes, I am *that* interested in Jython). Seems that Frank Wierzbicki and Otmar Humbel have been quite busy in the past 2 months! :) Keep your fingers crossed. I hope Frank will finish the new website and get back to Jython itself soon. (Not to discount anything that Frank has been doing, but IMHO the old website was just fine.) For myself, I've been looking into Jython code whenever I have the time, I hope I can help one day and contribute instead of just checking those two lists like 4 times a week :) From johnjsal at NOSPAMgmail.com Wed Mar 29 13:55:50 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 29 Mar 2006 18:55:50 GMT Subject: a hobbyist's dilemma In-Reply-To: References: Message-ID: Benji York wrote: > John Salerno wrote: >> Now that I've learned much of Python, I'm sort of stuck with what to >> do with it. > > http://www.pythonchallenge.com/ > > You can (thank|curse) me later. > -- > Benji York "This challenge is fantastic. Clever, addictive and really gets your mind working. I feel like I'm playing Myst.", James Tauber after finishing level 22. wow, i'm automatically interested now :) From superprad at gmail.com Fri Mar 31 11:08:11 2006 From: superprad at gmail.com (PyPK) Date: 31 Mar 2006 08:08:11 -0800 Subject: member variables in python In-Reply-To: <442d4b03$1_2@newspeer2.tds.net> References: <1143819190.360242.314830@z34g2000cwc.googlegroups.com> <442d4b03$1_2@newspeer2.tds.net> Message-ID: <1143821291.915307.157060@g10g2000cwb.googlegroups.com> ok I reason I was going with globals is that i use this variable in another class something like this along with above testflag = 0 class AA: def __init__(...): def methos(self,...): global testflag testflag = xx class BB: def __init__(...): def method2(..): if testflag: print "do this" is there a better way to access this if we go with what you mentioned in another class .. I wanted to avoid globals thats the reason i am looking for better solution .. From deets at nospam.web.de Mon Mar 27 13:12:04 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 27 Mar 2006 20:12:04 +0200 Subject: front end GUI In-Reply-To: <1143479013.659230.91000@j33g2000cwa.googlegroups.com> References: <1143479013.659230.91000@j33g2000cwa.googlegroups.com> Message-ID: <48qo7jFl9g9mU1@uni-berlin.de> DataSmash schrieb: > I'm looking for software to create a simple GUI to execute python code > for users in the office. > The GUI would need a couple text boxes for user input and some option > buttons and check boxes. > Can anyone recommend free software that doesn't require a huge learning > curve? > My python skills are probably a 3 or 4 on a scale from 1 to 10. Use the shipped tkinter. Diez From tjreedy at udel.edu Mon Mar 20 22:57:49 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 20 Mar 2006 22:57:49 -0500 Subject: Python 2.5 Schedule References: <1142667600.257048.315910@z34g2000cwc.googlegroups.com> <1f7befae0603201704pddadc21ie20e7460a7bb4724@mail.gmail.com> Message-ID: "Tim Peters" wrote in message news:1f7befae0603201704pddadc21ie20e7460a7bb4724 at mail.gmail.com... >> For more details about the plan for Python 2.5, see: >> >> http://www.python.org/doc/peps/pep-0356/ > > Looks like links to PEPs are completely hosed at the moment. For > example, the link above displays an empty directory, and > > http://www.python.org/doc/peps > > displays a directory full of empty directories. Back up now, at least for me. tjr From nancyhowes at yahoo.com Wed Mar 22 16:38:32 2006 From: nancyhowes at yahoo.com (Nancy) Date: 22 Mar 2006 13:38:32 -0800 Subject: python linking Message-ID: <1143063512.682459.95050@g10g2000cwb.googlegroups.com> When i link with python2.4.a i get this error. ld: Dwarf Error: Invalid or unhandled FORM value: 14. I am NOT using the gcc compiler but the linux icc compiler. Google hits blame it on gcc compiler binutils being out of date. i dont think thats the problem here. thanks. From andre.roberge at gmail.com Thu Mar 9 07:15:10 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 9 Mar 2006 04:15:10 -0800 Subject: question about slicing with a step length In-Reply-To: References: <1141871828.993855.208580@v46g2000cwv.googlegroups.com> Message-ID: <1141906509.952096.165310@p10g2000cwp.googlegroups.com> Terry Reedy wrote: > > John Salerno wrote: > >> Given: > > > numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > > can someone explain to me why > > > numbers[10:0:-2] results in [10, 8, 6, 4, 2]? > > It appears that s[i:j:-1] is s[(j+1):(i+1)] .reverse()'ed. For 'numbers', > this is 10, 9, 8, 7, 6, 5, 4, 3, 2]. Then take every other item. Why the > +1? Don't know and not my intuitive expectation. I just know that > extended slicing was developed for and until recently pretty much > restricted to numeric (now numpy). > It's not simply "+1". >>> a = range(10) >>> a[9:0:-2] [9, 7, 5, 3, 1] >>> a[10:0:-2] [9, 7, 5, 3, 1] >>> a[11:0:-2] [9, 7, 5, 3, 1] >>> a[42:0:-2] [9, 7, 5, 3, 1] > Steven D'Aprano > > I think the documentation is misleading/incomplete when > > it comes to negative strides for extended slices. > > and Andre "Agreed!" also, and you three aren't the only ones. Maybe some > day I will read the source, think about it more, and post a suggested > revision for comment ... or maybe someone will beat me to it. I, myself, think that the slicing behaviour is broken in this case. >From the little I understand (without looking at the source), adjustment on the boundaries of the slicing "request" (the first 2 numbers) is done first, to make them positive and, I believe, ensure that they do not extend beyond the boundaries of the sequence. Then, the actual stepping through is performed. In my (most likely not-well informed enough opinion), the behaviour should be the following: from [i: j: k], if k > 0 and j <= i : return [] if k< 0 and j >= i : return [] otherwise, build the following list of numbers: i, i+k, i+2*k, until i +n*k >= j (if k>0; use <= if k<0) where the last number is excluded, i.e. [0: 2: 1] = list(0, 1) *Then*, exclude from the list just built any negative numbers, or any number greater than the length of the sequence to be sliced. So, [10:0:-2] would yield the following list of numbers [10, 8, 6, 4, 2] before trimming; applying this to range(10), would end up with result in trimming "10" from the list built. Thus, we are looking at indices [8, 6, 4, 2] of range(10), which happen to be the numbers [8, 6, 4, 2] in this case. We should end up with the same list if we ask for [42:0:-2]. This is not the observed behaviour, as we get [9, 7, 5, 3, 1]. If we ask Python to do >>> a[0:10:2] we get [0, 2, 4, 6, 8] which is correct. It seems to me that the following (pseudo-code, not valid Python) a[2:10:2] == a[8:0:-2].reversed() should be true, just like a[1:10:1] == a[9:0:-1].reversed() is true. I *suspect* that "boundary adjustments" are performed first before creating a sequence of indices, so that there is less "trimming" (as described above) for the sake of efficiency ... and that this is not done properly. Then again, perhaps I simply don't understand what slices are supposed to do.... Andr? > > Terry Jan Reedy From sushant.sirsikar at gmail.com Fri Mar 31 00:18:50 2006 From: sushant.sirsikar at gmail.com (sushant.sirsikar at gmail.com) Date: 30 Mar 2006 21:18:50 -0800 Subject: How to debug python code? Message-ID: <1143782330.199836.221880@v46g2000cwv.googlegroups.com> hi, I am new to Python programming.I am not getting exactly pdb.Can anyone tell me effective way to debug python code? Please give me any example. Looking for responce. Thank You. Sushant From aleaxit at yahoo.com Sun Mar 26 16:26:07 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Mar 2006 13:26:07 -0800 Subject: Accessing func_name from inside a function References: <1143309619.566327.173640@j33g2000cwa.googlegroups.com> Message-ID: <1hct6ag.nhhp9h1744vlpN%aleaxit@yahoo.com> James Thiele wrote: > I'd like to access the name of a function from inside the function. My > first idea didn't work. > > >>> def foo(): > ... print func_name > ... > >>> foo() > Traceback (most recent call last): > File "", line 1, in ? > File "", line 2, in foo > NameError: global name 'func_name' is not defined So, define it -- as a function, of course: def func_name(): import sys return sys._getframe(1).f_code.co_name def foo(): print func_name() def bar(): print func_name() No doubt you'll object that the internals of func_name are "ugly", but the point is that it can be hidden anywhere you like, so its internals are as irrelevant as they would be if it was a built-in. Alex From larry.bates at websafe.com Fri Mar 3 11:08:41 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 03 Mar 2006 10:08:41 -0600 Subject: string stripping issues In-Reply-To: <1141335954.481084.277030@p10g2000cwp.googlegroups.com> References: <1141335954.481084.277030@p10g2000cwp.googlegroups.com> Message-ID: orangeDinosaur wrote: > Hello, > > I am encountering a behavior I can think of reason for. Sometimes, > when I use the .strip module for strings, it takes away more than what > I've specified. For example: > >>>> a = ' Hughes. John\r\n' > >>>> a.strip(' ') > > returns: > > 'ughes. John\r\n' > > However, if I take another string, for example: > >>>> b = ' Kim, Dong-Hyun\r\n' > >>>> b.strip(' ') > > returns: > > 'Kim, Dong-Hyun\r\n' > > I don't understand why in one case it eats up the 'H' but in the next > case it leaves the 'K' alone. > Others have explained the exact problem, I'll make a suggestion. Take a few minutes to look at BeautifulSoup. It parses HTML code and allows for extractions of data from strings like this in a very easy to use way. If this is a one-off thing, don't bother. If you do this commonly, BeautifulSoup is worth a little study. -Larry Bates From larry.bates at websafe.com Mon Mar 20 15:58:21 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 20 Mar 2006 14:58:21 -0600 Subject: Win32 ActiveX with COM support In-Reply-To: <1142866971.191129.313460@g10g2000cwb.googlegroups.com> References: <1142866971.191129.313460@g10g2000cwb.googlegroups.com> Message-ID: danbrwn at gmail.com wrote: > I am creating a web application where I access a database on a SQL > server machine from local networked PC's via Javascript and HTML. > Unfortunately, Microsoft does not allow the ado intervace to fire > events back using Javascript or VBScript. I am trying to figure out how > to notifiy each client that is connected to the server whenever the > database changes. What I think might work well is to have a client > activeX component built with Python embedded in the html page that > receives event notification from a server component embedded in an ASP > page or maybe an HTML I don't know yet. At any rate, Can I create a COM > server / client component set with Python? > You can most certainly create COM server with Python. This sounds like a job for AJAX (asynchronous javascript and xml). Use javascript xmlrpc client code to asynchronously talk to a xmlrpc server application (you can write in python+twisted). If you choose to go this way, you might want to take a look here: http://developer.yahoo.net/yui/ Hope information helps. -Larry From fredrik at pythonware.com Thu Mar 30 10:40:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 30 Mar 2006 17:40:52 +0200 Subject: a hobbyist's dilemma References: <122nqan6hrb579a@corp.supernews.com> Message-ID: John Salerno wrote: > One like I'd like to learn is how to use Python with MySQL, but I just > can't get MySQL to work on my computer, so I'm at a dead end there. > Seems like the best option for cataloging though. if you want to play with SQL and Python's DB-API *without* having to install server stuff, pysqlite is a good choice: http://initd.org/tracker/pysqlite From dananrg at yahoo.com Fri Mar 3 04:21:45 2006 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: 3 Mar 2006 01:21:45 -0800 Subject: PythonWin: any way to delete all objects without exiting and without doing it with "del"? In-Reply-To: <1141293267.991614.156170@i39g2000cwa.googlegroups.com> References: <1141250922.615071.68700@i39g2000cwa.googlegroups.com> <87wtfd7r4c.fsf@voodoo.myself> <1141293267.991614.156170@i39g2000cwa.googlegroups.com> Message-ID: <1141377705.762385.224680@i40g2000cwc.googlegroups.com> Steven, does your technique fix my problem? Would that delete the objects I've created within a program if I suffix my code with it? From lycka at carmen.se Thu Mar 23 08:35:14 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 23 Mar 2006 14:35:14 +0100 Subject: datetime iso8601 string input In-Reply-To: References: <1140714826.044272.253460@t39g2000cwt.googlegroups.com> Message-ID: skip at pobox.com wrote: > Why not > > dt = datetime.datetime(*time.strptime(s, "%Y-%m-%dT%H:%M:%S")[0:6]) > > ? Maybe due to neglection of the 7th commandment? Most of the other commandments can be ignored while coding Python, but the 7th certainly applies here. http://www.lysator.liu.se/c/ten-commandments.html As I've written before, the ISO 8601 spec contains many variations in date formats. Making a full ISO 8601 parser is probably possible if we ignore time deltas, but it's hardly worth the effort. Writing something that parses a few percent of the possible ISO 8601 messages and calling that an ISO 8601 parser seems silly to me. With code like Skip's above it's obvious what kind of strings are handled. In typical applications, one such format is enough, and this needs to be properly specified. In a recent case I wrote the spec like this: "The timestamp shall be an ISO 8601 combination of UTC date and time with complete representation in extended format, with representation of fractions of seconds with up to six decimals preceeded by a full stop as decimal sign. E.g. 2005-06-20T13:42:55.2425Z" Despite my verbosity here, someone who didn't follow the example, would still be able to write ISO 8601 strings following the requirements above that we won't parse, since I didn't actually write that dates should be written as year-month-day. For a brief summary of some of the allowed variation see http://hydracen.com/dx/iso8601.htm From riklaunim at gmail.com Tue Mar 21 12:16:14 2006 From: riklaunim at gmail.com (=?ISO-8859-2?Q?piotr_mali=F1ski?=) Date: Tue, 21 Mar 2006 17:16:14 +0000 Subject: creating website script in Myghty Message-ID: <1f7f7cf70603210916p25947238jc5fb4a9e5f5b94b8@mail.gmail.com> I'm learning Myghty from few weeks and now I'm making a simple forum script ;) and I have problem finding few things in python that I need: - how to strip all HTML tags leaving the text / strip all code (python/other) from a string? - how to highlight a python/html/other code (result in HTML code)? From timr at probo.com Thu Mar 23 03:39:10 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 23 Mar 2006 08:39:10 GMT Subject: Can't get the real contents form page in internet as the tag "no-chche" References: <1143080278.976802.233340@u72g2000cwu.googlegroups.com> Message-ID: "dongdong" wrote: > >using web browser can get page's content formally, but when use >urllib2.open("http://tech.163.com/2004w11/12732/2004w11_1100059465339.html").read() > >the result is > >CONTENT="0;URL=http://tech.163.com/04/1110/12/14QUR2BR0009159H.html"> >content="no-cache">?y??'??a?3??... > >,I think the reson is the no-cache, are there person would help me? No, that's not the reason. The reason is that this includes a redirect. As an HTML consumer, you are supposed to parse that content and notice the tag, which says "here is something that should have been one of the HTTP headers". In this case, it wants you to act as though you saw: Refresh: 0;URL=http://tech.163.com/04/1110/12/14QUR2BR0009159H.html Pragma: no-cache In this case, the "Refresh" header means that you are supposed to go fetch the contents of that new page immediately. Try using urllib2.open on THAT address, and you should get your content. This is one way to handle a web site reorganization and still allow older URLs to work. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From onurb at xiludom.gro Fri Mar 31 06:55:47 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 31 Mar 2006 13:55:47 +0200 Subject: How to search HUGE XML with DOM? In-Reply-To: <1143803831.939208.190850@v46g2000cwv.googlegroups.com> References: <1143803831.939208.190850@v46g2000cwv.googlegroups.com> Message-ID: <442d1905$0$21119$626a54ce@news.free.fr> Sullivan WxPyQtKinter wrote: > a relation database has admiring search efficiency when the database is > very big (several thousands or tens of thousands of records). But my > current project is based on XML, for its tree-like data structure has > much more flexibility; and DOM, which could be manipulated just like a > tree. However, how to establish such a XML data base for search when it > contains 10,000 records (One record usually contain 10~30 tags) or > more? > > My search needs: > 1. Search and return all the record (an element) with specific id. > 2. Search and return all the record whose child nodes has a specific id > or attribute. > > the xml.dom.minidom object is too slow when parsing such a big XML file > to a DOM object. while pulldom should spend quite a long time going > through the whole database file. How to enhance the searching speed? > Are there existing solution or algorithm? Thank you for your > suggetion... - have a look at cElementTree ? - store your XML as persistant objects in a ZODB instance, then use ZODB catalog for queries ? - index relevant data in a DB (RDBMS, Berkeley, whatever...) ? - have a look at 4suite (http://4suite.org/index.xhtml) ? 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 dwahler at gmail.com Thu Mar 16 19:34:24 2006 From: dwahler at gmail.com (David Wahler) Date: 16 Mar 2006 16:34:24 -0800 Subject: My Generator Paradox! References: <1142554666.740989.303350@p10g2000cwp.googlegroups.com> Message-ID: <1142555664.005331.235110@z34g2000cwc.googlegroups.com> vbgunz wrote: > I am afraid that this is the first time in which I would probably need > something explained to me as if I were a little child. I am having a > hard time getting this through my thick skull. What in the world is > wrong with this!? > > ''' ########################################################### ''' > > def generatorFunction(sequence=['item1', 'item2', 'item3']): > for item in sequence: > yield item > > yieldedValue = generatorFunction() > > '''this seems to work perfectly.''' > print '-' * 32 > print yieldedValue # > print yieldedValue.next() # item1 > print yieldedValue.next() # item2 > print yieldedValue.next() # item3 > > '''this is where things don't make any sense!''' > print '-' * 32 > print generatorFunction() # > print generatorFunction().next() # item1 > print generatorFunction().next() # item1 > print generatorFunction().next() # item1 > > ''' ########################################################### ''' > > the first set of calls assigned to yieldedValue work but the second set > without assignment don't. I asked for help on this at #python (I love > those people in there!) and was told the following... > generatorFunction() is a call (obvious) when calling the second set, I > am resetting the iteration and this explains why I only and always get > item1. > > ok. *but* why in the world does the first set of calls work? > technically, isn't yieldedValue == generatorFunction() on a name basis? > I mean isn't the following technically the same? > > generatorFunction() > yieldedValue = generatorFunction() > > aren't they both the same? [snip] In that short example, they happen to be different, but equivalent, objects, but that will not always be the case. Consider this: >>> a = generatorFunction() >>> b = generatorFunction() >>> print a.next() item1 Now a and b are both generators for generatorFunction, but calling a.next() again will return 'item2', while calling b.next() will return 'item1'. The value returned by generatorFunction is an object, which has an internal state that makes it distinct from other objects of the same type. So once your yieldedValue has been altered by calling the next() method, it is no longer equivalent to a fresh instance of the generator. -- David From felipe.lessa at gmail.com Mon Mar 27 22:45:26 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 28 Mar 2006 00:45:26 -0300 Subject: what is the the best way to express following: In-Reply-To: References: <_uOdnaBMCLmcPLXZRVn-uA@comcast.com> Message-ID: <1143517526.4490.49.camel@kenshin> Em Seg, 2006-03-27 ?s 18:43 -0800, James Stroud escreveu: > Here is a suggestion > > todo = {(int, long):abc, (str,):afg, (tuple, list):ijk} > todo[type(key)]() Maybe... todo = {(int, long): abc, basestr: afg, (tuple, list): ijk} (y for x,y in todo.iteritems() if isinstance(key, x)).next()() Forget it! Damn, that's too unpythonic! (or perlish =) -- Felipe. From adapt.her.adapter at gmail.com Thu Mar 23 11:09:02 2006 From: adapt.her.adapter at gmail.com (adapt.her.adapter at gmail.com) Date: 23 Mar 2006 08:09:02 -0800 Subject: Python has a new Logo In-Reply-To: <1143128619.670174.282160@t31g2000cwb.googlegroups.com> References: <1143128619.670174.282160@t31g2000cwb.googlegroups.com> Message-ID: <1143130141.407691.139650@v46g2000cwv.googlegroups.com> Yawn. Go start indenting, and stop using Perl. If Python has such a nice logo, why waste any more time with Perl? From steve at holdenweb.com Sat Mar 4 06:57:12 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 04 Mar 2006 11:57:12 +0000 Subject: build windows module for python-2.4 In-Reply-To: <1141463963.256000.273820@v46g2000cwv.googlegroups.com> References: <1141463963.256000.273820@v46g2000cwv.googlegroups.com> Message-ID: william at opensource4you.com wrote: > Does any one having working python 2.4 compiler can give some details > on how to set it up ? > > I've read lot of different website, but some are outdated, others > referencing dead links, ... > > I would just use an existing python 2.3 module (VC6) to python-2.4. > I think the best is to recompile it with VC7.1, but how to setup the VC > environements? > > Thanks. > http://www.vrplumber.com/programming/mstoolkit/ did it for me! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From fredrik at pythonware.com Wed Mar 15 06:20:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Mar 2006 12:20:02 +0100 Subject: WORKAROUND References: <4417d37c$0$76222$892e7fe2@authen.yellow.readfreenews.net> <4417e8a4$0$58687$892e7fe2@authen.yellow.readfreenews.net> Message-ID: Could you perhaps use basic netiquette stuff, such as sticking to the same sub- ject line for followup posts in the same thread, and including a least some trace of the post you're commenting on ? (this would be less of a problem if everyone was reading your posts in a news- reader, but this group is available in many different forms...) From sandro at e-den.it Wed Mar 29 13:45:43 2006 From: sandro at e-den.it (Sandro Dentella) Date: Wed, 29 Mar 2006 18:45:43 GMT Subject: gtk.spinbutton and set_value Message-ID: Hi all, why my spinbutton doesn't show '120'? why, if I write in a number, it is reset to 0 wen Enter is pressed? TYA sandro import gtk w = gtk.Window() spin = gtk.SpinButton() w.add(spin) w.show_all() spin.set_value(120) gtk.main() -- Sandro Dentella *:-) http://www.tksql.org TkSQL Home page - My GPL work From johnjsal at NOSPAMgmail.com Sat Mar 25 16:05:11 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 25 Mar 2006 16:05:11 -0500 Subject: a somewhat off-topic question about linux In-Reply-To: References: <_oedne4wPJ9DPrjZnZ2dnUVZ_tWdnZ2d@rcn.net> Message-ID: Duncan Booth wrote: > John Salerno wrote: > >> I'm interested in trying out Linux, probably Ubuntu, but I was wondering >> which distribution you guys like to use (because it's a pain trying to >> decide!) and you guys are smart. > > If you just want to try out Linux then a very easy way is to use VMWare > Player: download it from http://www.vmware.com/products/player/. You can > then run almost any Linux you wish directly on your windows system, no need > to reboot or anything. Start with Browser Appliance which is a cut-down > installation of Ubuntu (but it is configured so that things like the > clipboard interact properly with Windows clipboard, and you can share files > by sharing folders on windows and connecting to them from Ubuntu). Then you > can use the package manager (on the System menu) to install Python and > other packages (when it asks for a password use 'vmware' if you are using > the default 'vmware' user). > > You need about 2Gb of free disk space to install and use VMWare and Browser > appliance: all of the Linux file system is stored in one file which expands > as required up to 9.5Gb maximum (it helps performance if you keep the file > defragmented: use contig.exe from www.sysinternals.com). > > Once you have Vmware installed, as well as Ubuntu, you can also download > Linux images for Novell/Suse, RedHat and literally dozens of other versions > of Linux and Unix variants, some preconfigured for specific applications > try them out and then throw them away. The only limits are your disc space. > >> And to keep it Python related, I'll also ask, is there anything special >> I need to know about using Python on Linux? Do any things change, or can >> it be used just as I use it on Windows? >> > The main difference is that it is much easier to install packages which are > part of the Ubuntu distribution: just run up the package manager, select > the ones to install and download and install happen automatically. > Thanks! From Aiwass333 at gmail.com Fri Mar 31 11:16:45 2006 From: Aiwass333 at gmail.com (RunLevelZero) Date: 31 Mar 2006 08:16:45 -0800 Subject: cd burning In-Reply-To: <1143819301.978901.161460@v46g2000cwv.googlegroups.com> References: <1143819301.978901.161460@v46g2000cwv.googlegroups.com> Message-ID: <1143821805.657282.293580@u72g2000cwu.googlegroups.com> I am hopeing something has developed myself. I have been waiting awhile. I simply don't want to use cdrecord or cdrdao. If I had the know how I would be working on it but I believe this is a massive undertaking and rather hard to accomplish. I do hope this happens very soon though. Libburn might be of some use to you? I know FreeBSD compiled some binding for python but the main libburn site only seems to officially have ruby binding atm. http://icculus.org/burn/. From neurogasm at gmail.com Fri Mar 24 19:01:39 2006 From: neurogasm at gmail.com (Kun) Date: Fri, 24 Mar 2006 19:01:39 -0500 Subject: imap folder scanner In-Reply-To: References: Message-ID: Marco Carvalho wrote: > On 3/24/06, Sebastjan Trepca wrote: > >> m.select('myfolder') > > Some attention is required here to retrieve subfolders. > Some imap servers like Cyrus and Courier uses "INBOX.subfolder" to > access subfolders. > -- > 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 so i have used the following code and have successfully saved a list of senders as a string. however, the string has much more information than just the email address and i am wondering what is the best way to parse the email address out of the entire string. sample string: >>> print status, senders OK [('460 (BODY[HEADER.FIELDS (FROM)] {46}', 'From: Friend \r\n\r\n'), ')', ('462 (BODY[HEADER.FIELDS (FROM)] {37}', 'From: Kun \r\n\r\n'), ')'] how do i just get the two email addresses out of there? my code is: from imaplib import * import getpass m = IMAP4("xxxxxxxx") m.login('xxxxxx', 'xxxxxxx') m.select('Inbox') status, data = m.search(None,'(SUBJECT "BIKES")') assert status=='OK', "Error. Message: %s"%data data = data[0] #you get your results in a list and search returns only one result assert data,"No results" #cool, we have results, but IMAP's search command only returns IDs so we have to fetch #msgs now status,senders = m.fetch(data.replace(' ',','),'(BODY.PEEK[HEADER.FIELDS (FROM)])') assert status=='OK', "Error. Message: %s"%data print senders From garylinux at gmail.com Sun Mar 12 23:33:58 2006 From: garylinux at gmail.com (garylinux at gmail.com) Date: 12 Mar 2006 20:33:58 -0800 Subject: How to best update remote compressed, encrypted archives incrementally? In-Reply-To: References: Message-ID: <1142224438.002674.12730@j33g2000cwa.googlegroups.com> Would rsync into a remote encrypted filesystem work for you? From gregory.petrosyan at gmail.com Tue Mar 21 15:12:13 2006 From: gregory.petrosyan at gmail.com (Gregory Petrosyan) Date: 21 Mar 2006 12:12:13 -0800 Subject: Why "class exceptions" are not deprecated? Message-ID: <1142964066.915730.297000@i40g2000cwc.googlegroups.com> 1) From 2.4.2 documentation: There are two new valid (semantic) forms for the raise statement: raise Class, instance raise instance 2) In python: >>> raise NameError Traceback (most recent call last): File "", line 1, in ? NameError >>> help(NameError) Help on class NameError in module exceptions: ... >>> raise 0 Traceback (most recent call last): File "", line 1, in ? TypeError: exceptions must be classes, instances, or strings (deprecated), not i nt So, if it's a bug in documentation, it should be corrected. Otherwise, (IMHO!) raising classes should be deprecated. Does raising class make sence? As for me, I can't find any usefull case for it. From paul at boddie.org.uk Mon Mar 6 05:56:13 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 6 Mar 2006 02:56:13 -0800 Subject: Package organization: where to put 'common' modules? References: <1141419542.750676.176150@z34g2000cwc.googlegroups.com> <44098830$1_3@newspeer2.tds.net> <1141599776.392714.28350@i39g2000cwa.googlegroups.com> <1141605355.963705.3860@z34g2000cwc.googlegroups.com> <1141610344.910017.263540@j52g2000cwj.googlegroups.com> Message-ID: <1141642573.473775.86170@i40g2000cwc.googlegroups.com> fortepianissimo wrote: > Paul Boddie wrote: > > fortepianissimo wrote: > > > Hm this doesn't work. Say I have the following directory structure: > > > > > > A > > > |--- util > > > | |--- foo.py > > > | > > > |--- B > > > |--- bar.py > > > > > > > > > And bar.py has this line > > > > > > from util import foo [...] > Placing code modifying sys.path in main would be a problem if the > utility loading line is at the beginning of the module - error would > occur before sys.path can be modified. Well, I suppose you could start your module with... import sys, os sys.path.append(some_nasty_tricks_with_paths) Although I don't really recommend this, since such code is going to get run as the modules get imported, and this could cause some additional complications if various things then conspire to import the "wrong" modules somewhere else in your system. > It is especially true for me since I need to load these "common > functionality" not just for testing - they are necessary to implement > the functionality of the module. > > Besides, adding code to manipulate sys.path in *every* module that > needs the common functionality module seems to be quite a hassle... I suppose you're one of the people who may benefit from the relative import mechanisms in Python 2.5. Myself, I can't see why it's so hard to write... from A.util import foo [...] > I need to import this common functionality not just for testing code, > so it probably doesn't matter if I separate the testing code from the > module itself. I stopped running modules inside packages directly precisely because of the behaviour you've seen. I haven't experienced many problems with my "test from the outside" approach since. > In addition, the "common functionality" is "common" only for the system > I'm building - they are probably not that useful for general purposes. > So placing them in an absolute path (like site packages) doesn't make a > lot of sense. Right. So it's just a matter of making sure that everything can import such functionality without either triggering circular imports or mixing up "internal" modules with "external" ones (as my example showed). Paul From scott.daniels at acm.org Fri Mar 3 15:05:31 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 03 Mar 2006 12:05:31 -0800 Subject: white space in expressions and argument lists In-Reply-To: References: <44074fea@nntp0.pdx.net> Message-ID: <44089fb1@nntp0.pdx.net> Magnus Lycka wrote: > .... Touching more lines of code than you actually need will > both make it difficult for a reviewer to understand what > has changed (although good diff tools can be told to > ignore pure whitespace changes) ... Such features have a nasty interaction with languages that use significant whitespace; you might miss a re-blocking change while suppressing the hassles from the extra "prettifying" spaces. --Scott David Daniels scott.daniels at acm.org From onurb at xiludom.gro Tue Mar 14 15:48:36 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 14 Mar 2006 21:48:36 +0100 Subject: Very, Very Green Python User In-Reply-To: <1142215118.291132.130490@e56g2000cwe.googlegroups.com> References: <1142215118.291132.130490@e56g2000cwe.googlegroups.com> Message-ID: <44172c5b$0$2083$626a54ce@news.free.fr> hanumizzle at gmail.com wrote: > I have used Perl for a long time, but I am something of an experimental > person and mean to try something new. Most of my 'work' with Vector > Linux entails the use of Perl (a bit of a misnomer as it is not now a > paid position -- I am not yet even out of K-12), and there a lot of > things I love about it. I can look past a number of misfeatures in > Perl, but I am surprised to see that Python has very few (that I know > of). Most of them are documented here, it would seem: > http://www.c2.com/cgi/wiki?PythonProblems. Seems that this page is sometimes just plain wrong and somewhat outdated. Let's see some of them: 1/Memory Management The reference implementation uses reference counting, the worst-performing memory management scheme there is Actually, Python uses *both* reference-counting and a garbage collector. 2/ No Ternary If Well... actually true, but not such a major annoyance. NB : the "tuple_dispatch" option works well if you know how-to python. IOW, you can avoid useless evaluation with a simple lambda : result = (lambda: action_if_true, lambda : action_if_false)[test]() 3/ Dynamic Typing Err... Actually, this is not a problem, Sir, it's a feature. 4/ Speed Never been a problem for me so far. 5/ Ugly mechanism for privates This is *not* a mechanism for "privates". This is a mechanism to protect some crucial implementation attributes from being *accidentally* overriden in a child class. 6/ SelfDotSyndrome As for 3, this is definitively a feature. I've always used the implicit 'this' in Java and C++ anyway. > Is the Python debugger > fairly stable? can't tell, almost never had a use for it. > More than > anything else, I would like to have a powerful OO environment where I > do not have to worry about the debugger sucking ass. What makes you think you have such a need for a debugger ? > A couple blemishes I'm concerned about, though: > > Python closures are apparently very poor, In Python, encapsuling state is better done with objects. Once you'll get a better understanding of Python's object model, you'll find out that there's not such a need for more powerfull closures (well, that's MHO at least). Amongst other things, functions and methods are objects, and any other class can be made callable if you implement a method for the call operator... > but from what I can surmise > of the PyGTK2 page, instances of objects are dynamic enough to add new > methods, so you get your callbacks, at least. You don't even need this to use callbacks. Remember, functions and methods are objects, and other objects can be callable too... > Double-underscore methods are rewritten with the class name? That's an > ugly hack, Ever looked at what a C++ compiler do to symbols ?-) > but remember I'm coming from Perl. Talking about ugky hacks... !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From enterr at gmail.com Mon Mar 20 17:31:00 2006 From: enterr at gmail.com (Atanas Banov) Date: 20 Mar 2006 14:31:00 -0800 Subject: Python equivalent of Perl-ISAPI? In-Reply-To: <1142878315.504465.191490@z34g2000cwc.googlegroups.com> References: <1142657781.197131.222440@g10g2000cwb.googlegroups.com> <1142790625.227356.48830@i40g2000cwc.googlegroups.com> <1142865756.452672.57930@v46g2000cwv.googlegroups.com> <1142877087.441903.240840@v46g2000cwv.googlegroups.com> <1142878315.504465.191490@z34g2000cwc.googlegroups.com> Message-ID: <1142893860.425691.127640@v46g2000cwv.googlegroups.com> rurpy at yahoo.com wrote: > Steve Holden wrote: > > rurpy at yahoo.com wrote: > > > > Pure cgi is too slow. "Active Scripting" means ASP, yes? > > > I need something that will do cgi scripts (a lot of which I already > > > have > > > and can modify but don't want to rewrite extensively, partly because > > > of time issues, partly because I want to preserve some degree of > > > portability back to a unix environment.). I want something that does > > > for IIS what mod_python does for apache. Fastcgi looked scary even > > > on unix plaforms, seems like an act of desperation on Windows, > > > > > Yes, ASP is Active Scripting. > > > Except I need cgi, not asp, for the reasons i gave. it seems to me you have no clear idea what you need. you say you have a lot of CGIs written but you don't clarify if that is Python or Perl. since you look for python intergration, it seems they are in python, however in previous posting you say you'll have to revert to Perl for solution. it just doesnt make sense! if you use Perl, you will have to REWRITE the scripts and if you do so, it's unclear why wouldnt you use a superior technology like PHP/ASP/JSP - any of those is way easier to manage. it's also unclear why don't you use apache on windows, if mod_python is your poison. here is how i imagine you have the layers: [scripts (CGI?)] [glue] [web server (IIS?)] where the discussion is about the "glue" between them. you say CGI is too slow for you, so you will want something maintaining the CGI programming model, but faster. this thing is called FastCGI - but you are unhappy about it either. there is no way any perl "glue" can solve your problem between your web server and your python scripts whatsoever. you'll have to re-code the scripts for perl. From paul at boddie.org.uk Tue Mar 7 20:10:14 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 7 Mar 2006 17:10:14 -0800 Subject: Type Hinting vs Type Checking and Preconditions References: <1141764243.936880.324240@i39g2000cwa.googlegroups.com> Message-ID: <1141780214.569684.198670@v46g2000cwv.googlegroups.com> Roy Smith wrote: > In article <1141764243.936880.324240 at i39g2000cwa.googlegroups.com>, > "Tom Bradford" wrote: > > > > def multiplyByTwo(value): > > return value * 2 [...] > The question is, what is the function *supposed to do*? Without knowing > what it is *supposed to do*, it is impossible to say for sure whether > returning "1414" is correct or not. Indeed. And I don't think arithmetic-based examples are really very good at bringing out the supposed benefits of type declarations or are very illustrative when reasoning about type systems, mostly because everyone assumes the behaviour of the various operators without considering that in general the behaviour is arbitrary. In other words, people look at expressions like "a * b" and say "oh yes, numbers being multiplied together producing more numbers" without thinking that "a" might be an instance of "Snake" and "b" might be an instance of "Reptile" and the "Snake.__mul__" method (or perhaps the "Reptile.__rmul__" method) might produce a range of different things that aren't trivially deduced. > Consider two different functions: > > def multiplyByTwo_v1(value): > """Returns the argument multiplied by 2. If the argument is a > string representation of an integer, another string is returned > which is the string representation of that integer multiplied > by 2. > """" > return value * 2 > > def multiplyByTwo_v2(value): > """Returns the argument multiplied by 2. > """" > return value * 2 > > The first one should return "28" when passed "14". If it returns "1414", > it's broken. I know this seems rather silly and pedantic, but it's an > important point. I've done some work on this kind of thing which actually specialises functions/methods and produces something resembling that quoted above, and I believe that various other works produce similar specialisations when reasoning about the behaviour of Python programs. Specifically, you'd write the first version like this: def multiplyByTwo_v1(value): if isinstance(value, int): return int.__mul__(value, 2) elif isinstance(value, string): return string.__mul__(value, 2) else: raise RuntimeError Really, you'd want to avoid having a single specialisation, having separate ones for each "incoming type", although that might be hard to arrange in every case. Paul P.S. Have a look here for some simple (and now quite dated) examples: http://www.boddie.org.uk/python/analysis.html Specifically, here: http://www.boddie.org.uk/python/analysis-summaries.html (A good test of CSS standards compliance if nothing else!) I'll hopefully make a new release at some point in the near future which tries to do a better job at deducing the various types and invocation targets. From cito at online.de Tue Mar 28 17:27:43 2006 From: cito at online.de (Christoph Zwerschke) Date: Wed, 29 Mar 2006 00:27:43 +0200 Subject: doctest, unittest, or if __name__='__main__' In-Reply-To: <1143512909.811663.32850@j33g2000cwa.googlegroups.com> References: <1142974528.143287.326360@e56g2000cwe.googlegroups.com> <1143512909.811663.32850@j33g2000cwa.googlegroups.com> Message-ID: lollipopenator at gmail.com wrote: > Hi there Christopher, I was wondering if you (or anyone reading this ) > could quickly summarize the ways in which unittest is unpythonic, or > point me to somewhere which discusses this. > Is this 'consensus opinion' or mainly your own opinion? It is just a consequence from the fact that unittest is actually a port from JUnit (Java) to Python, i.e. a consequence of trying to emulate a standard framework that many programmers are already familiar with, which is essentially not a bad idea. However, if you try to counterfeit Java programming, your code won't be effective or elegant in Python. > Is there a summary somewhere (in addition to the Zen of Python thingy) > of what kinds of things are 'pythonic' and why they are considered so? > I see it referred to a lot, and am starting to get a feel for it in > some areas but not others. It's probably never been listed completely (and it also changes slowly as the language evolves). Programming in an unpythonic way is like driving a nail with a screwdriver. Here are some more explanations: http://faassen.n--tree.net/blog/view/weblog/2005/08/06/0 http://mail.python.org/pipermail/europython/2005-April/004975.html -- Christoph From eric_brunel at despammed.com Thu Mar 30 03:31:17 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 30 Mar 2006 10:31:17 +0200 Subject: GUI in python References: <1143670803.148098.21940@z34g2000cwc.googlegroups.com> Message-ID: On 29 Mar 2006 14:20:03 -0800, wrote: > Hi, > > I am a python newbie and have used it for about a month. I want to make > a simple GUI app in Python ( I take input form user and do processing > and show results). > > Which gui package is good for me. I need to do it quick and I would not > want a long learning curve. > > I was taking look at wxPython, pyGTK etc. > > > Please suggest me the most simplest and easiest one as I dont need > super cool aesthetics just a plain simple GUI app. This site will allow you to decide for yourself based on the important criteria for you: http://www.awaretek.com/toolkits.html HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From wbpurzoreaqfra at qfr.ay Sun Mar 19 13:38:50 2006 From: wbpurzoreaqfra at qfr.ay (Jochem Berndsen) Date: Sun, 19 Mar 2006 19:38:50 +0100 Subject: Relative paths in mod_python References: Message-ID: <2b48d$441da5e1$503999bd$5991@news.chello.nl> Ivo van der Sangen wrote: > I was wondering if I could use relative paths in a mod_python script. At > the moment I am defining a constant string > "/path/to/dir/where/script/resides". > [snip] You can use Python's built-in __file__ variable. It is set to the absolute location of your script. You can then use one of the built-in functions in the `os' module (I forgot which) to extract the directory your script resides. Jochem. -- E-mail address encrypted using ROT13. From No.Spam at Spam.none Tue Mar 28 15:07:34 2006 From: No.Spam at Spam.none (I. Myself) Date: Tue, 28 Mar 2006 20:07:34 GMT Subject: trying to use popen2() to communicate with C program In-Reply-To: <4i1j22ld8oh3fnd0e15pj9f24his39igp9@4ax.com> References: <4i1j22ld8oh3fnd0e15pj9f24his39igp9@4ax.com> Message-ID: Dennis Lee Bieber wrote: > On Tue, 28 Mar 2006 18:02:46 GMT, "I. Myself" > declaimed the following in comp.lang.python: > > >> The compile C program, commer.exe, writes a line of text to its stdout. >> The python program does not receive it; it never gets to print "Got here >> 2". Commer.exe does begin execution. Here's commer.c, but there >> appears to be no problem with it. Commer.exe can be executed alone, and >> it behaves as expected. >> >> > Try flushing stdout... Many C runtimes detect when stdout is not a > console and go to a buffered output mode; without a flush, it may be > holding data until a (disk) block is filled... > That worked! I put fflush(stdout); after the printf() statement, and that fixed it. Thanks! Mitchell Timin I'm proud of http://ANNEvolve.sourceforge.net. I'm currently working on a major update of the SailChallenge package. If you want to write software, or articles, or do testing for ANNEvolve, let me know. Humans may know that my email address is zenguy at shaw789 dot ca. (Remove the 3-digit number.) From martin.witte at gmail.com Sun Mar 19 17:28:19 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 19 Mar 2006 14:28:19 -0800 Subject: Pycrypto - active ?? In-Reply-To: <1142804398.710230.117640@j33g2000cwa.googlegroups.com> References: <1142804398.710230.117640@j33g2000cwa.googlegroups.com> Message-ID: <1142807299.141313.306980@i40g2000cwc.googlegroups.com> Well, the homepage of Pycrypto (http://www.amk.ca/python/code/crypto) was modified las in December 2005 - quite recent imo. It is used e.g. in the paramiko package (http://www.lag.net/paramiko/) for the most(?) used ssh implementation in Python, so my guess it is active. From brandon.mcginty at gmail.com Sat Mar 11 16:34:26 2006 From: brandon.mcginty at gmail.com (brandon.mcginty at gmail.com) Date: Sat, 11 Mar 2006 14:34:26 -0700 Subject: Dictionary project Message-ID: <00ad01c64553$93d01e90$6400a8c0@D1FWTS61> Hi All, First, I hope this post isn't against list rules; if so, I'll take note in the future. I'm working on a project for school (it's not homework; just for fun). For it, I need to make a list of words, starting with 1 character in length, up to 15 or so. It would look like: A B C d E F G ... Z Aa Ab Ac Ad Ae Aaa Aab Aac Etcetera. I've looked on Google, and on the python lists at python.org, and haven't found any code that I can adapt. I've also tried to adapt some code from Perl, but not knowing the language very well, I wasn't very successful. If there is adaptable code on the internet that I've missed, please let me know, and I'll go on my marry way in search of it. Any help would be appreciated. Thanks Much, Brandon McGinty Brandon.mcginty at gmail.com -- No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.1.375 / Virus Database: 268.2.1/279 - Release Date: 3/10/2006 From fredrik at pythonware.com Wed Mar 29 11:20:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 29 Mar 2006 18:20:26 +0200 Subject: Doc suggestions (was: Why "class exceptions" are not deprecated?) References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com><1143070060.384366.25480@z34g2000cwc.googlegroups.com><1143574346.354680.136060@i39g2000cwa.googlegroups.com><34bb7f5b0603290047o21b9a1b7k64cdd206f604fc10@mail.gmail.com> <34bb7f5b0603290752p48a1b818x4570d189153cbcdc@mail.gmail.com> <34bb7f5b0603290753w42d463d8gd975523a5ae7d7ab@mail.gmail.com> Message-ID: Ed Singleton wrote: > > alright, I got bored and uploaded a copy of the current Python tutorial to > > > > http://pytut.infogami.com > > Damn. You beat me to it by an hour. > > http://singletoned.infogami.com/_special/index oops. sorry for that. > > I had a nightmare with character encodings (mainly because I'm > > terrible with them). I have a script written that does it all for me, > > but it keeps choking on characters. I just tried randomly converting > > things to Unicode at various points for over an hour until it worked. sounds weird. iirc, there were only one page that contained non-ascii characters, and the latest html2text.py script had no problems dealing with that one. > Also, your looks better than mine. did you look at it before or after I added the new stylesheet? ;-) > Did you write a script to do the table of contents too? nope; I did that all by hand. I plan to write some scripts to get contents *out* of infogami, though, but that'll have to wait for some other day. anyway, do you want to keep your version, or should we "standardize" on the pytut version ? and are there any willing community contributors out there? From alan.franzoni.xyz at gmail.com Fri Mar 10 18:07:52 2006 From: alan.franzoni.xyz at gmail.com (Alan Franzoni) Date: Sat, 11 Mar 2006 00:07:52 +0100 Subject: Which GUI toolkit is THE best? References: <441172c2$1@news1.ethz.ch> Message-ID: <1jk98ti5l75jq$.185esrz0xojp3$.dlg@40tude.net> invitro81 on comp.lang.python said: > again to make a choice is difficult; is there also some guy liking pyqt > is it worse or should it be avoided because of the licencing policy for > qt (which I also like..)? > > * Which one is the most fun to program with? > * Which one is the most easy to learn? > * Which one looks best? > * Which one is the most productive to program with? Those are all hard questions. You might as well have asked 'which is the best web framework'. It's not easy to tell ^_^ It highly depends on which tasks you're aiming at. wxPython is a pretty good 'all-round' and cross-platform library, and includes some non-graphical features. It's got a drawback: it's a wrapper for the wxwidgets library, and hence it's not very pythonic; you can solve part of its unpythonicness using wax, which is not very well documented at the time. wxGlade can be used to design GUI apps with little effort. pyGTK works well, too. Recent versions perform well and are good looking on Windows systems as well as Linux and Macs (if you provide an X server). It's very well documented (better than wxPython, in my opinion) and its license is quite permissive. It's unpythonic just like wxPython. Glade and Gazpacho can be used to design GUI apps in a visual way. pyGUI is a pyGTK-based graphic library which is designed from scratch to be pythonic. It seems very, very promising but I can't tell you if it's production-stable since I've tested it just a couple of times. It may be the funniest and more productive toolkit ever. FLTK was interesting but seems to lack maintenance and support, pyQT is a bit 'unfree' for most uses. Tkinter is quite old stuff. -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Rremove .xyz from my address in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From justin.frost at gmail.com Thu Mar 23 15:36:17 2006 From: justin.frost at gmail.com (MakaMaka) Date: 23 Mar 2006 12:36:17 -0800 Subject: boost python tutorial In-Reply-To: References: <1143141465.996635.232150@t31g2000cwb.googlegroups.com> Message-ID: <1143146177.600800.317890@v46g2000cwv.googlegroups.com> I checked and it is. I can't use news servers at work b/c of the firewall. Is there another way to access this mailing list? From http Sat Mar 18 23:33:00 2006 From: http (Paul Rubin) Date: 18 Mar 2006 20:33:00 -0800 Subject: Can I use a conditional in a variable declaration? References: <1142741039.554379.182170@g10g2000cwb.googlegroups.com> Message-ID: <7xveub9hqb.fsf@ruckus.brouhaha.com> volcs0 at gmail.com writes: > a = (if a == "yes": "go ahead": "stop") > > is there such a form in Python? I tried playing around with lambda > expressions, but I couldn't quite get it to work right. This has been the subject of huge debate over the years. The answer is Python doesn't currently have it, but it will be added to a coming version: See http://www.python.org/doc/peps/pep-0308/ To do it in the most general way with lambda expressions, use (untested): a = (lambda: iffalse_expression, lambda: iftrue_expression)[bool(condition)]() That makes sure that only one of the target expressions gets evaluated (they might have side effects). There are various more common idioms like a = (condition and iftrue_expression) or iffalse_expression which can go wrong and evaluate both expressions. It was a bug caused by something like this that led to conditional expressions finally being accepted into Python. From cito at online.de Mon Mar 20 07:36:23 2006 From: cito at online.de (Christoph Zwerschke) Date: Mon, 20 Mar 2006 13:36:23 +0100 Subject: cmp() on integers - is there guarantee of returning only +-1 or 0? In-Reply-To: <1hcgdwr.zg61xysokadwN%aleaxit@yahoo.com> References: <441dd94c$0$20108$834e42db@reader.greatnowhere.com> <1hcgdwr.zg61xysokadwN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > wrote: >> Why not >> >> def sign(n): >> return n and n/abs(n) or 0 > > If you assume n is a number, the 'or 0' appears redundant (if you don't > so assume, then the abs(n) and the division are doubtful;-). Without the 'or 0' it is also more consistent with the behavior of your function that the sign of a float is also a float. One issue is that division should be normally avoided because it is a costly operation and can lead to rounding errors. Maybe performance is is not a problem for ints and floats, but if you are planning to use the function on long ints, I would consider using something like: def sign(x): return x>0 and 1 or x<0 and -1 or 0 def sign(x): return (x>0)-(x<0) -- Christoph From a at b.c Mon Mar 13 13:57:23 2006 From: a at b.c (Caleb Hattingh) Date: Mon, 13 Mar 2006 20:57:23 +0200 Subject: Python IDE: great headache.... In-Reply-To: <1142120002.912902.69630@i40g2000cwc.googlegroups.com> References: <1142120002.912902.69630@i40g2000cwc.googlegroups.com> Message-ID: Hi Being a Delphi user at work, I know what you mean :) The best python IDE I have found is Stani's Python Editor (SPE), and I think Stani himself replied to your message as well. It integrates wxGlade, which is nice for form-building, although I don't really do much of that with the python code I write. My only gripe with SPE is that the memory usage, while SPE is running, slowly climbs and climbs, and after several hours that python thread running SPE is using several hundred megabytes of RAM. I usually just restart it. It seems as if the effect is pronouced when running code in the IDE. Other than that, I now use SPE instead of Vim for python editing, which is a big step for me. SPE is quite slick; some ways to go, but certainly on the right track. The built-in code-completion is a godsend. Hope this helps Caleb Sullivan WxPyQtKinter wrote: > IDLE is no longer satisfactory for me. Other IDEs make me very > confused. Really do not know which one to use. > > I use WinXP sp2 for current development. > > So far as I know, Eclipse + PyDev + PyDev Extension is perfect for > source code editing. Since I am really not sure how to use the debugger > module, I really do not know how to add watch to variables etc. Anyone > knows if this platform is a good one? > > I hope that an IDE should be featured with: > 1. Grammar Colored highlights. > 2. Manage project in a tree view or something alike, ie, a project file > navigator. > 3. Code collapse and folding. > 4. Code auto-completion: especially prompting function parameters when > I am typing a function previously defined by myself. Like the one in > Visual Studio series. > 5. Debugging: Breakpoints, conditional pause. watch for variables.step > into, over and out of a function. > What about other IDEs? Since I do not need GUI development. More over, > the free-of-charge IDE is highly preferred. > 6.Indentation management like in IDLE: press ctrl+[/] to modify the > identation of a line or a block. > > In addition, I have seen quite a few editors, which are definitely not > what I want. > > Thank you so much for suggestions. > From Allerdyce.John at gmail.com Fri Mar 17 13:01:39 2006 From: Allerdyce.John at gmail.com (Allerdyce.John at gmail.com) Date: 17 Mar 2006 10:01:39 -0800 Subject: unicode error Message-ID: <1142618498.987917.325940@j33g2000cwa.googlegroups.com> I have this python code: print >> htmlFile, "
"; But that caues this error, and I can't figure it out why. Any help is appreicate File "./run.py", line 193, in ? print >> htmlFile, "
"; UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 9: ordinal not in range(128) Thanks. From sizelji at insightbb.com Wed Mar 29 22:01:13 2006 From: sizelji at insightbb.com (Jim Sizelove) Date: Thu, 30 Mar 2006 03:01:13 GMT Subject: a hobbyist's dilemma In-Reply-To: References: Message-ID: John Salerno wrote: > Now that I've learned much of Python, I'm sort of stuck with what to do > with it. I'm not a professional programmer, so I don't really have a use > for Python now. But I really want to come up with some neat uses for it > (for fun, and so I don't just start forgetting it right after I learned > it). Here are some other ideas: You can find sample code for project ideas at Useless Python (http://uselesspython.com) and the Python Cookbook (http://aspn.activestate.com/ASPN/Python/Cookbook/). Hang out at the python tutor mailing list (http://mail.python.org/mailman/listinfo/tutor) and learn from others and learn by helping others. Enjoy your python adventures, Jim Sizelove From http Thu Mar 9 00:06:05 2006 From: http (Paul Rubin) Date: 08 Mar 2006 21:06:05 -0800 Subject: advice on this little script References: <2bSdncqWK7aJN5LZRVn-vA@rcn.net> <120vb889343kd1@corp.supernews.com> Message-ID: <7xhd68nr5u.fsf@ruckus.brouhaha.com> John Salerno writes: > > for x in range(minutes,0,-1): > > sleep(60.0) > > print minutes, 'minutes remaining' > > > Nice! Cross off another line! I feel like Hemingway. :) Besides the bug mentioned, I don't think you should really do it that way, since sleep(60.0) might not sleep for exactly 60 sec (it could be longer or shorter). Preferable is something like (untested): now = time.time() sleep_until = now + 60*minutes while now < sleep_until: print int((now - sleep_until)/60), 'minutes remaining' sleep (60) now = time.time() You might actually want to stop sleeping a little bit early (say if you wake up 5 seconds before sleep_until), or round the message to the nearest number of minutes, etc. From fredrik at pythonware.com Sat Mar 11 05:24:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 11 Mar 2006 11:24:57 +0100 Subject: Can not find a file in CMD model python when everything is OK in IDLE References: <1142072226.386475.313160@p10g2000cwp.googlegroups.com> Message-ID: "Sullivan WxPyQtKinter" wrote: > I use python in Windows XP platform. I find that if I write a .py file > in a directory, such as windows desktop, in which a file named > 'ticket.txt' is located: > > f=open("\ticket.txt") > print f.read() "\t" is a tab character: >>> print '\ticket.txt' icket.txt try opening r"\ticket.txt" or "/ticket.txt" instead. From golgote at gmail.com Sat Mar 11 09:37:01 2006 From: golgote at gmail.com (Bertrand Mansion) Date: Sat, 11 Mar 2006 15:37:01 +0100 Subject: New python.org site In-Reply-To: <140mqj7t7y2s5$.r1fgnfqmwl29$.dlg@40tude.net> References: <140mqj7t7y2s5$.r1fgnfqmwl29$.dlg@40tude.net> Message-ID: <6a246d8e0603110637q13339803u2db266c3ed98a534@mail.gmail.com> On 3/11/06, Thorsten Kampe wrote: > There have recently been threads here about the website. Maybe the > discussion there gives you some information needed: > > * http://groups.google.com/group/comp.lang.python/browse_thread/thread/f4c1585fe379d8ad/11fd0062787e374c?tvc=2&q=group%3Acomp.lang.python+insubject%3Apython.org&hl=en#11fd0062787e374c > * http://groups.google.com/group/comp.lang.python/browse_thread/thread/23c5ee82f22757f3/2696c44b8385a8e8?tvc=2&q=group%3Acomp.lang.python+insubject%3Apython.org&hl=en#2696c44b8385a8e8 > * http://groups.google.com/group/comp.lang.python/browse_thread/thread/330af3b245145f7e/667bb15d53f0c555?tvc=2&q=group%3Acomp.lang.python+insubject%3Apython.org&hl=en#667bb15d53f0c555 I have read those, they look like Slashdot comments where you get some people trying to post a good joke... They don't answer my simple questions: 1. Who is maintaining python.org ? 2. Where is the site code/design available ? 3. Is the last redesign a solo or a community effort ? From enleverlesX.XmcX at XmclaveauX.com Thu Mar 16 07:34:14 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Thu, 16 Mar 2006 13:34:14 +0100 Subject: Python compiler References: Message-ID: <44195b7a$0$29204$8fcfb975@news.wanadoo.fr> Hi! Bonjour ! Apr?s, vous pourrez aussi fr?quenter le newsgroup : fr.comp.lang.python qui a l'avantage d'?tre en fran?ais. ? bient?t. Michel Claveau From johnjsal at NOSPAMgmail.com Wed Mar 1 09:54:35 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 01 Mar 2006 14:54:35 GMT Subject: Use empty string for self In-Reply-To: References: <1141170846.619246.163470@t39g2000cwt.googlegroups.com> <120a94q7qnhb97@corp.supernews.com> Message-ID: James Stroud wrote: > py> def doittoit(it): > ... print it.whatzit > ... > py> class It: > ... whatzit = 42 > ... def doittoit(self): > ... print self.whatzit > ... > py> anit = It() > py> doittoit(anit) > 42 > py> It.doittoit(anit) > 42 > py> anit.doittoit() > 42 > > > If you get this example, I'm pretty sure you will understand "self" and > its necessity. I do get it. I think I will just have to get used to seeing the 'self' argument but understanding that it's not really something that is always passed in. I'm trying to train myself to see def doittoit(self) as def doittoit() Of course, that might not be a good strategy, because I know when it isn't used as an instance method (is that C terminology?), then you must explicitly pass the self argument. From msoulier at gmail.com Fri Mar 3 09:03:13 2006 From: msoulier at gmail.com (msoulier) Date: 3 Mar 2006 06:03:13 -0800 Subject: do design patterns still apply with Python? References: <8SINf.1718$No6.40137@news.tufts.edu> Message-ID: <1141394593.588174.321660@z34g2000cwc.googlegroups.com> Personally, I find many of the design patterns apply but require modification. For example, the Factory pattern is mostly to work around the fact that it's difficult in Java and C++ to dynamically load classes. Not so in Python, especially with exec. A simple configuration file and an exec call can replace an entire Factory pattern, with the same result. The ideas are fine, but sometimes it's best to keep things simple. I find that DP junkies don't tend to keep things simple. From mahs at telcopartners.com Thu Mar 16 09:51:32 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 16 Mar 2006 06:51:32 -0800 Subject: Large algorithm issue -- 5x5 grid, need to fit 5 queens plus some squares In-Reply-To: References: <1142484909.490742.152390@j33g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh wrote: > totalgeekdom at gmail.com wrote: > >> The problem I'm trying to solve is. >> There is a 5x5 grid. >> You need to fit 5 queens on the board such that when placed there are >> three spots left that are not threatened by the queen. > > when you're done with your homework (?), you can compare it with > Guido's solution: > > http://svn.python.org/view/python/trunk/Demo/scripts/queens.py > > > > > Or, Tim Peters' generator-based one: http://svn.python.org/view/python/trunk/Lib/test/test_generators.py Michael From paul at boddie.org.uk Thu Mar 30 11:58:50 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 30 Mar 2006 08:58:50 -0800 Subject: LDTP 0.4.0 released !!! References: <442B163B0200004400005175@mcclure.wal.novell.com> <1143715621.527601.178270@j33g2000cwa.googlegroups.com> Message-ID: <1143737930.677580.240720@e56g2000cwe.googlegroups.com> Ben Finney wrote: > > Most projects have a consistent "what is this thing and why should you > care" paragraph in every release announcement; this would be the place > to make clear the association with the forum where it's posted. Indeed. There have been a few announcements in comp.lang.python.announce where it hasn't even been clear what the announced project is about, let alone whether it's in Python or not - the latter we just have to assume is the case. Paul P.S. I suspected the Python connection because it appears that a number of desktop-related projects use Python, particularly in association with GNOME and Sun Microsystems - reading Planet GNOME isn't a total waste of time, after all. ;-) From enleverlesX.XmcX at XmclaveauX.com Mon Mar 20 16:26:21 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Mon, 20 Mar 2006 22:26:21 +0100 Subject: how to make script interact with another script References: Message-ID: <441f2044$0$18343$8fcfb975@news.wanadoo.fr> Hi! Few ways : - use TCP/IP server+client (this can also run via a LAN or Internet) - use mmap (this can run Python<=>Python, Python<=>Ruby, etc.) - use a file (and win persistance) - use telepathy (Oups! Sorry, the module is not published yet) - etc. MCI From dinko.tenev at gmail.com Fri Mar 24 04:42:14 2006 From: dinko.tenev at gmail.com (Dinko Tenev) Date: 24 Mar 2006 01:42:14 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1143024937.827420.104100@i39g2000cwa.googlegroups.com> <20060322141400.1A00.1.NOFFLE@dthierbach.news.arcor.de> <1143110872.284192.325230@u72g2000cwu.googlegroups.com> <20060323134326.C29.0.NOFFLE@dthierbach.news.arcor.de> <1143134775.887696.5000@z34g2000cwc.googlegroups.com> <20060323212800.79D.0.NOFFLE@dthierbach.news.arcor.de> Message-ID: <1143193333.963153.23850@g10g2000cwb.googlegroups.com> Dirk Thierbach wrote: > Dinko Tenev wrote: > >> > I don't see immediately how exactly this is going to work. Unless I'm > >> > very much mistaken, a FSA in the classical sense will accept or reject > >> > only after the whole sequence has been consumed, and this spells > >> > exponential times. > > >> Exponential in respect to what? > > > With respect to sequence length. > > But you cannot get rid of this. Consider S = {a, b}, W = {a}. > Then there are |S|^n result elements for n > 1, and you have to enumerate > all of them. Yes, but then, they are in the target set. The point here is whether you can generate S^n - W in Theta( n * |S^n - W| ), which may be dramatically different from Theta( n * |S^n| ). > The best thing one can hope for is to just actually process those > elements that are really in the result set. With the FSM, you're > getting at least close to that. If the FSA has to consume the whole sequence, you're only impoving performace by a constant factor. > The automaton is: > > S: a -> A, b -> B > A: a -> A > B: b -> B The target set is specified as S^n - W, where W is everything matching (.*a.*b|.*b.*a). Following the construction procedure in point, this exclusion set is matched exactly by my DFA with S initial and F final. Then, swapping final and non-final states makes {S, A, B} final, and F non-final. Your DFA above may be equivalent, but to me it is far from clear exactly what algorithm would build it from the given data. > > Looking at the minimal DFA for the above example, it may be more > > appropriate to detect being in a state from which there's no path to a > > final state: > > This cannot happen, because minimizing removes all those states. > (Or, in case you have a different definition of automaton in mind: > There'll be just one "stuck" state, where all transitions that never > go to a final state end up. Remove this state, and you'll end up > with the other definition). I have to admit that I've never considered this before, but as I'm thinking of it now, a block of such states will never split by minimization, so they're bound to end up together as a single state, which can then be eliminated. I can see your point now. > >> I guess one could even optimize on that: In the minimal automaton, > >> every state has some transition sequence that will end up in a final > >> state. Annotate each state with the minimum number of steps for > >> such a sequence. While walking the automaton, keep the maximum > >> number of letters to produce in a variable. If this number is small > >> then the number in the annotation, stop and backtrace. > > > I don't think this could cut efficiently for patterns like *a*b. > > The point is not to "cut efficiently", the point is to enumerate > only those words that are actually in the result set. No, this is not the point. Naive filtering already does that. By "cutting efficiently" I mean skipping over search sub-trees that don't contain any results from the target set. If you can do this, you can enumerate the target set in time proportional to its size, not to the size of the search space, which is the point. Cheers, Dinko From forusa99 at yahoo.com Mon Mar 27 14:45:34 2006 From: forusa99 at yahoo.com (forusa99) Date: Mon, 27 Mar 2006 19:45:34 -0000 Subject: Linux developer with Python and Perl Message-ID: I have a 6 months contract position open in one of my client sites at San Jose, CA. Here is the job description: General Linux Application Developer: Job Description: Develop a wide variety of user space features using C, Java, Python, Perl, and various shell scripts. Development includes, writing functional/design specifications, implementing the design, unit testing the implementation and supporting the implementation through a test cycle. Skills Required: 1. 5-10 years commercial SW development experience. 2. 3+ years of commercial Linux development experience. 3. 3+ years of Java. 4. 2+ Years C++ experience. 5. Ability to work with little direct supervision in a very agile development group Excellent written and verbal communication skills They are really looking for someone who has embedded programming experience utilizing Java on a Linux platform. They do not want to see front end web developers. Preferred: Python and Perl Would appreciate sending me resumes to me ASAP. Thanks From mogmios at mlug.missouri.edu Thu Mar 9 15:46:29 2006 From: mogmios at mlug.missouri.edu (Michael) Date: Thu, 09 Mar 2006 12:46:29 -0800 Subject: Any python HTML generator libs? In-Reply-To: <1141936438.584242.129220@z34g2000cwc.googlegroups.com> References: <1141936438.584242.129220@z34g2000cwc.googlegroups.com> Message-ID: <44109425.7040003@mlug.missouri.edu> > Will XSTL be useful? Is my problem somewho related with XML-SIG? > Looking forward to your precious suggestion. > XSLT is powerful but a royal pain in the arse. Just writing some Python to generate your HTML would probably be a lot easier for you. -- Michael McGlothlin, tech monkey Tub Monkey http://www.tubmonkey.com/ From tgrav at mac.com Wed Mar 22 13:11:51 2006 From: tgrav at mac.com (Tommy Grav) Date: Wed, 22 Mar 2006 13:11:51 -0500 Subject: Newbie: Print question Message-ID: Being new to Python I am getting a result I do not understand. I have a code that reads in a set of lines from a file, slits up the lines and puts information into a list of class objects. obslist = mpc.Read_Observations(options.in_fname) ; for testobs in obslist: print testobs.printmpc() where the class is defined as class MPC_Observation: def __init__(self,iname,iepoch,ira,idec,imag,iobscode): self.name = iname self.epoch = iepoch self.ra = ira self.dec = idec self.obscode = iobscode self.mag = imag def printmpc(self): if self.mag!="": print "%14s %12.5f %5.2f %6.2f %8.3f %3i" \ % (self.name, self.epoch, self.ra,self.dec,self.mag,self.obscode) else: print "%14s %12.5f %5.2f %6.2f %3i" \ % (self.name, self.epoch, self.ra,self.dec,self.obscode) But when I run the code I get a bunch of lines with None output Albiorix 2005.00000 133.03 17.77 695 None Albiorix 2005.00000 133.03 17.77 695 None Albiorix 2005.00000 133.03 17.77 695 None Albiorix 2005.00000 133.03 17.77 695 None Albiorix 2005.00000 133.01 17.78 695 None I don't understand where these None's are coming from. Anyone care to enlighten me? 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: From paul at boddie.org.uk Thu Mar 16 13:40:29 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 16 Mar 2006 10:40:29 -0800 Subject: Cheese Shop: some history for the new-comers References: <44126523$0$1016$afc38c87@news.optusnet.com.au> <1142529722.091761.316050@p10g2000cwp.googlegroups.com> Message-ID: <1142534429.506300.87620@j33g2000cwa.googlegroups.com> Harald Armin Massa wrote: > > one of the richest people on earth did define what developers are: > > http://www.ntk.net/ballmer/mirrors.html I was wondering when someone would mention the "developers, developers, developers" Ballmer song-and-dance incident: clearly, he isn't chanting about internal Microsoft project teams. Paul From tjreedy at udel.edu Wed Mar 1 14:26:09 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 1 Mar 2006 14:26:09 -0500 Subject: type = "instance" instead of "dict" References: <1141069989.763239.191140@u72g2000cwu.googlegroups.com><44035966$1_2@newspeer2.tds.net><1141072746.685948.251040@j33g2000cwa.googlegroups.com><440370ce$1_2@newspeer2.tds.net><1141081177.003471.139820@t39g2000cwt.googlegroups.com><1141087585.910134.17650@j33g2000cwa.googlegroups.com><1141172214.657248.256480@t39g2000cwt.googlegroups.com> <44055069.1060904@REMOVEMEcyber.com.au> Message-ID: "Steven D'Aprano" wrote in message news:44055069.1060904 at REMOVEMEcyber.com.au... > Cruella DeVille wrote: > >> This is off topic, but if read the documentation is the answere to >> everything why do we need news groups? > > Because "read the documentation" is NOT the answer to > everything. However, it was the answer to your question. Google can also answer some questions posted here in less time than it takes to post here. >> I wouldn't ask here without trying to find the solution on my own >> first. Unfortunately, such enterprise is not universal. More than once, someone has asked something like "Hey, Newbie here. Are there any Python programs that can mung frobits?" So I type "Python program mung frobits" into the Google bar of my browser and an answer pops up in a second. tjr From steve at REMOVETHIScyber.com.au Fri Mar 10 19:48:56 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 11 Mar 2006 11:48:56 +1100 Subject: Why python doesn't use syntax like function(, , x) for default parameters? References: <44115054$0$14937$834e42db@reader.greatnowhere.com> Message-ID: On Fri, 10 Mar 2006 12:06:57 +0300, Dmitry Anikin wrote: > I mean, it's very convenient when default parameters > can be in any position, like > def a_func(x = 2, y = 1, z): > ... > (that defaults must go last is really a C++ quirk which > is needed for overload resolution, isn't it?) I'm confused... it looks to me like the defaults are *first*, not last, in the above definition. We write from left to write in English, so normal convention in English is that first -> last, not last <- first. > and when calling, just omit parameter when you want to > use defaults: > a_func(, , 3) Can you do this? another_func(,,,4,,,,) That looks like bug-city to me. (Did I mean 4 to go in the fourth position or fifth?) In any case, given the way Python defaults work, the commas are superfluous. There is no ambiguity: def f(w, x, y=1, z=1): pass Positional arguments without defaults *must* go first, and must be supplied: f(5, 6) => w=5, x=6, y=1, z=1 Commas would be pointless: f(5, 6, , ) isn't needed, because the first and second arguments are already assigned to the w and x arguments before the first empty comma is spotted. You can't do this: f(, , 5, 6) => w,x = default, y=5, z=6 because w and x don't have defaults. > There are often situations when a function has independent > parameters, all having reasonable defaults, and I want to > provide just several of them. In fact, I can do it using > keyword parameters, but it's rather long and you have to > remember/lookup names of parameters. And you think it is easier to remember the position of parameters rather than their names? -- Steven. From fredrik at pythonware.com Sun Mar 12 11:09:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Mar 2006 17:09:35 +0100 Subject: Cheese Shop: some history for the new-comers References: <44126523$0$1016$afc38c87@news.optusnet.com.au> <44141D59.6050806@pollenation.net><4414234F.7020605@pollenation.net><44142CAA.9080407@pollenation.net> <1142178342.382120.236130@j33g2000cwa.googlegroups.com> Message-ID: Paul Boddie wrote: > It's clear that people use the term "Python developer" similarly to > "Oracle developer", where you don't get many people in the wild > actually developing Oracle products themselves, and so the term has an > established meaning of someone developing with that technology. Thus, > many people, especially those accustomed to using more corporate > technologies like Oracle or Java would see "Developers" or "Developer" > links and think of stuff they can develop with, rather than finished > applications or solutions, for example; it certainly wouldn't occur to > them that the links would point to some internal Oracle portal strictly > for Oracle development staff, some Sun portal for Java development > staff, or tools for working on the Python implementation. this assumes that the "developers" link lead to a page that's entirely useless for people developing with Python. that's not even true for today's "developer" page... (I'd solve this by adding disambiguation to the page itself, since people can arrive on it in many different ways. good information design is not only about what's on the front page...) From http Tue Mar 7 15:12:56 2006 From: http (Paul Rubin) Date: 07 Mar 2006 12:12:56 -0800 Subject: Cryptographically random numbers References: <1141515788.580039.98240@v46g2000cwv.googlegroups.com> <"1LXOf.449 97$H71.35174"@newssvr13.news.prodigy.com> Message-ID: <7xveuqnhdj.fsf@ruckus.brouhaha.com> Gervasio Bernal writes: > How can I generate a random string containing digits, symbols and > letters? I will use this random string for the key of a cryptographic > algorithm. Generally if this is a string that some human user has to type in, it's preferable to select some words randomly from a dictionary rather than use an easily-garbled string of symbols. If the string will be handled entirely by computers, just use a random string of bytes (like os.urandom(20)) without worrying about whether they're printable characters. If you really want a random-looking string of specific characters, a simple way is: usable_characters = string.letters + string.digits ... # generate one character from the set (repeat as needed) a,b = map(ord, os.urandom(2)) c = (a*256 + b) % len(usable_characters) Notice that the characters will have slightly unequal probability (unless the usable character set's size is a power of 2), but the effect on the output entry is insignificant. From zbir at urbanape.com Thu Mar 9 14:25:40 2006 From: zbir at urbanape.com (Zachery Bir) Date: Thu, 9 Mar 2006 14:25:40 -0500 Subject: Python Evangelism In-Reply-To: References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> <1141922861.541970.283350@j33g2000cwa.googlegroups.com> Message-ID: On Mar 9, 2006, at 12:04 PM, rtilley wrote: > What do you think of when you hear 'eggs'? Many people think 'rotten', > 'smelly' or something that made them throw-up once. The point of > this is > that names _matter_ and influence what others think even if only in a > subconscious way. I think you've got a lot of bottled up negativity. > I'll leave it at that. I like Python a lot. Technically, it's > awesome. I > don't think the language is bad... just the names associated with it. I'm betting you won't leave it at that. Zac From adelagon at gmail.com Fri Mar 31 12:42:08 2006 From: adelagon at gmail.com (Alvin A. Delagon) Date: Fri, 31 Mar 2006 17:42:08 +0000 Subject: CGIHTTPServer threading problems Message-ID: <442D69F0.1090704@gmail.com> I'm a simple python webserver based on CGIHTTPServer module: import CGIHTTPServer import BaseHTTPServer import SocketServer import sys import SQL,network from config import * class ThreadingServer(SocketServer.ThreadingMixIn,BaseHTTPServer.HTTPServer): pass cfg = params() print "XBOX Server started on port %s. Press Ctrl+C to kill Server" % cfg.port server = ThreadingServer((cfg.name,cfg.port),CGIHTTPServer.CGIHTTPRequestHandler) try: while 1: sys.stdout.flush() server.handle_request() except KeyboardInterrupt: print "Server killed" The my cgi scripts are stored in the cgi-bin folder. One cgi script in particular implements multi-threading and is supposed to be asynchronous but it's not working. The browser that requests on the cgi script tends to wait until the cgi script is done. I checked multi-threaded cgi script but I'm 100% percent sure that it has no problem since it worked as a mod_python script before. Anyone came across with this problem? From fredrik at pythonware.com Wed Mar 1 06:45:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 1 Mar 2006 12:45:34 +0100 Subject: pysqlite problem References: <1141212172.445009.230610@i39g2000cwa.googlegroups.com> Message-ID: bapolis at gmail.com wrote: > I'm getting the following error: > > pysqlite2.dbapi2.OperationalError: no such table: tbl1 > > Here's my code: > > from pysqlite2 import dbapi2 as sqlite > con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES) > cur = con.cursor() > cur.execute("select * from tbl1") > data = cursor.fetchall() > for record in date: > record[0], record[1] > > my installation versions: > > python 2.4.2 > pysqlite 2.0.7 > sqlite 3.3.4 > > I checked to make sure I have a table called tbl1. where? > I don't understand what's going on. Any ideas? last time I checked, connect(":memory:") creates a new blank database every time it is called. From davids at webmaster.com Mon Mar 6 04:30:23 2006 From: davids at webmaster.com (David Schwartz) Date: Mon, 6 Mar 2006 01:30:23 -0800 Subject: Setting timeout for read api References: <1141458799.669343.108080@i40g2000cwc.googlegroups.com> <7xpsl2mydo.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xpsl2mydo.fsf at ruckus.brouhaha.com... > "Swaroop" writes: >> PLS HELP..I am working on socket programming as part of my final year >> project. I want to know how to set a timeout on read api that reads >> from a socket. Is it possible using SIGALRM signal?Will setting >> O_NONBLOCK flag of the socket help? Is there any other way to do it? > You could do it with sigalrm but more common is to set a timeout on > the socket (see the settimeout method in the doc). You could also use > select with a timeout, and not read until the select tells you that > data is available. Just don't forget to set the socket non-blocking. DS From bearophileHUGS at lycos.com Sat Mar 4 16:22:24 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 4 Mar 2006 13:22:24 -0800 Subject: Open source reliability study Message-ID: <1141507344.446833.82140@u72g2000cwu.googlegroups.com> They have used a lot of time and money to find bugs in Python too: http://www.theregister.co.uk/2006/03/03/open_source_safety_report/print.html 0.32 defects per 1,000 lines of code in LAMP, it says. I hope they will show such Python bugs, so Python developers can try to remove them. From the bottom of the article: >Coverity said it would now engage with open source developers to improve code, and identify potential reasons for why some projects have more bugs than others.< Bye, bearophile From jess.austin at gmail.com Tue Mar 7 02:30:22 2006 From: jess.austin at gmail.com (jess.austin at gmail.com) Date: 6 Mar 2006 23:30:22 -0800 Subject: generators shared among threads References: <1141497912.606351.232440@j33g2000cwa.googlegroups.com> <1hbo9a3.1pfr3uy160d79iN%aleaxit@yahoo.com> Message-ID: <1141716622.587523.265790@u72g2000cwu.googlegroups.com> Thanks for the great advice, Alex. Here is a subclass that seems to work: from Queue import Queue from itertools import count class reentrantQueue(Queue): def _init(self, maxsize): self.maxsize = 0 self.queue = [] # so we don't have to override put() self.counter = count() def _empty(self): return False def _get(self): return self.counter.next() def next(self): return self.get() def __iter__(self): return self From johnjsal at NOSPAMgmail.com Wed Mar 29 22:10:53 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 29 Mar 2006 22:10:53 -0500 Subject: Uninstalling Python In-Reply-To: References: <122mankrkc6tb11@corp.supernews.com> Message-ID: <442b4d55$0$9411$c3e8da3@news.astraweb.com> Robert Kern wrote: > "Why is Python Installed on my Computer?" FAQ: > http://www.python.org/doc/faq/installed/ Most importantly from that link: Some Windows machines also have Python installed. At this writing we're aware of computers from Hewlett-Packard and Compaq that include Python. Apparently some of HP/Compaq's administrative tools are written in Python. From tzot at sil-tec.gr Sat Mar 4 05:18:03 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Sat, 04 Mar 2006 12:18:03 +0200 Subject: How to Mount/Unmount Drives on Windows? References: <1140919575.691402.70970@i40g2000cwc.googlegroups.com> Message-ID: On 25 Feb 2006 18:06:15 -0800, rumours say that dpickles at pacbell.net might have written: >Hello, >I do not know how to mount or unmount drives on Windows. I think that >it could possibly be done with a DOS command (using os.system()). mountvol is the command you want. I know it's in winxp, I think it was in win2k too. Check the Windows Help for its usage. PS another command that is most useful is netsh, especially for laptops. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From trevis.crane at gmail.com Thu Mar 2 12:51:33 2006 From: trevis.crane at gmail.com (orangeDinosaur) Date: 2 Mar 2006 09:51:33 -0800 Subject: newbie question In-Reply-To: <1141267810.025658.132610@e56g2000cwe.googlegroups.com> References: <1141242700.105093.317210@t39g2000cwt.googlegroups.com> <1141267810.025658.132610@e56g2000cwe.googlegroups.com> Message-ID: <1141321893.571481.306860@i40g2000cwc.googlegroups.com> Thanks!! This makes sense. And you were right about my misunderstanding. Michael Tobis wrote: > I think the answers so far are unnecessarily confusing and off the > mark. > > Here is what I think you think you want to know: > > 1) import only works once. If you try import again, it will see the > module already exists, and will ignore you > > 2) the functionality you think you want is reload. > >>> reload mymodule > will essentially reimport mymodule after the first time. > > However, what you think you want is not what you want, which is why the > experienced people are giving misleading and overcomplicated answers. > Normally reload is a fairly advanced feature and beginners don't need > it. > > Usually, an import statement invokes a module containing a bunch of > definitions (usually functions or classes, but sometimes even > constants), but it doesn't DO anything unless it is invoked as the main > program. > > So after you satisfy yourself that "reload" does what you want, try to > think about how you would work things so you don't need it. > > For instance, instead of something like > > #mystuff.py > > print "hello ", > print "world" > > # end of file > > > > >>> import mystuff > hello world > >>> import mystuff > > >>> > > is > > > > ### newstuff.py > > def newstuff(): > print "hello", > print " world" > > # end of file > > > > >>> from newstuff import newstuff > >>> newstuff() > hello, world > >>> newstuff() > hello, world > > > hth > mt From email at christoph-haas.de Sun Mar 12 13:51:06 2006 From: email at christoph-haas.de (Christoph Haas) Date: Sun, 12 Mar 2006 19:51:06 +0100 Subject: Class attributes newbie question (before I join a cargocult) In-Reply-To: <1142188575.187032.61390@v46g2000cwv.googlegroups.com> References: <1142188575.187032.61390@v46g2000cwv.googlegroups.com> Message-ID: <200603121951.08008.email@christoph-haas.de> Am Sonntag, 12. M?rz 2006 19:36 schrieb EP: > This is likely a stupid question, but I am confused about what is going > on with class attributes as far as whether they "stick". I ran across > this in a program I am writing, but have reproduced the behavoir below > - can someone point me in the right direction (thanks): > > class AttStickiness(object): > def __init__(self, myname="", mysex=""): > self.name=myname > self.sex=mysex ^--- sex > def changeSex(self, newsex=""): > self.mysex=newsex ^--- mysex You are not altering the same attribute. Cheers Christoph -- ~ ~ ".signature" [Modified] 1 line --100%-- 1,48 All From steve at holdenweb.com Sun Mar 5 21:24:34 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 06 Mar 2006 02:24:34 +0000 Subject: raw strings and \ In-Reply-To: <1141580826.470715.319020@i40g2000cwc.googlegroups.com> References: <1141548565.145199.145910@e56g2000cwe.googlegroups.com> <1141576051.081203.318010@e56g2000cwe.googlegroups.com> <1141580826.470715.319020@i40g2000cwc.googlegroups.com> Message-ID: plahey at alumni.caltech.edu wrote: > Hi, > > thanks for the reply. I was not aware of this in raw strings (and > frankly, don't like it... but who cares about that :-) ) > Healthy attitude! > When I needed embedded quotes in a raw string I went the triple quote > route: > > a = r'''check \' this''' > > which makes more sense to me. > But remember you could equally well have used a = "check \\' this" I presume you do *want* that backslash in there? If not, of course, then a = "check ' this" is by far the simplest way to represent what you want. because Python offers four different string quotes, each of which can be raw, there's always a way ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From http Sat Mar 4 01:31:49 2006 From: http (Paul Rubin) Date: 03 Mar 2006 22:31:49 -0800 Subject: idea: add an asynchronous exception class Message-ID: <7x3bhysotm.fsf_-_@ruckus.brouhaha.com> I'd like to suggest adding a builtin abstract class to Python called AsynchronousException, which would be a subclass of Exception. The only asynchronous exception I can think of right now is KeyboardInterrupt, so KeyboardInterrupt would become a subclass of AsynchronousException instead of being a direct subclass of Exception. There's been talk of adding ways of raising asynchronous exceptions across threads from user code, so those exceptions would also be subclassed from AsynchronousException. The reason for wanting this is the common idiom try: run_parrot_code() # might raise ParrotException except ParrotException: pass # or do some stuff except IOError: pass except: # run_parrot_code raised something unexpected print 'unexpected exception' raise The catchall except: block captures not only unexpected exceptions raised from the dynamic scope of the try: block, but also any asynchronous exception that might be raised. It should have a way to distinguish between those two cases, i.e. by checking whether the caught exception is an instance of AsynchronousException. That's better than checking for all known asynchronous exceptions explicitly and then having the code break when a new such exception gets added. Catchall "except" blocks are generally frowned on because of this issue but they're used all over the place anyway. The suggestion above is extremely simple to implement but there might be better ways to solve the problem. From kent at kentsjohnson.com Sun Mar 5 20:59:36 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sun, 05 Mar 2006 20:59:36 -0500 Subject: Package organization: where to put 'common' modules? In-Reply-To: <1141605355.963705.3860@z34g2000cwc.googlegroups.com> References: <1141419542.750676.176150@z34g2000cwc.googlegroups.com> <44098830$1_3@newspeer2.tds.net> <1141599776.392714.28350@i39g2000cwa.googlegroups.com> <1141605355.963705.3860@z34g2000cwc.googlegroups.com> Message-ID: <440b92c9$1_3@newspeer2.tds.net> Paul Boddie wrote: > Yes, Python does this - it puts the directory of bar.py (B in this > case) in sys.path, but not the directory in which you're sitting when > you run the program from the shell (A in this case). This seems to be OS dependent. If I put 'print sys.path' at the start of site.py (which does most of the setup of sys.path), one element of the path is an empty string. This is expanded by main() -> removeduppaths() -> makepath() -> os.path.abspath() to the current working dir. This is Python 2.4.2 on Win2K. Kent From steve at holdenweb.com Tue Mar 21 04:40:51 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 21 Mar 2006 09:40:51 +0000 Subject: user-supplied locals dict for function execution? In-Reply-To: <1142894077.918388.267480@i39g2000cwa.googlegroups.com> References: <1142875454.906993.126370@v46g2000cwv.googlegroups.com> <441eedbd$0$20865$636a55ce@news.free.fr> <1142879594.924929.96440@v46g2000cwv.googlegroups.com> <441f0623$0$23127$626a54ce@news.free.fr> <1142887575.402624.156050@e56g2000cwe.googlegroups.com> <441f29ec$0$31422$626a54ce@news.free.fr> <1142894077.918388.267480@i39g2000cwa.googlegroups.com> Message-ID: Lonnie Princehouse wrote: >>Beautiful is better than ugly. >>Explicit is better than implicit. >> >>>Err... I see no contradiction nor conflict here. > > > What to do when explicit is ugly and implicit is beautiful? Aye, > there's the rub. ;-) > Realise that sometimes explicitly ugly can be implicitly beautiful, and you will become enlightened. could-that-be-the-sound-of-one-hand-clapping-ly y'rs - steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From rich at addr.invalid Thu Mar 9 14:01:39 2006 From: rich at addr.invalid (Rich) Date: Thu, 09 Mar 2006 20:01:39 +0100 Subject: Learning different languages References: Message-ID: On Tue, 07 Mar 2006 23:44:56 +0100, Rich wrote: Well thanks for all your replies.There seem to be general agreement that it's best to learn one language at a time, which also is what makes most sense to me. I'm also glad to hear it's not a big problem to separate the different languages, in practice. The analogy with different spoken languages makes sense, yes, I have no problem at all in that respect. Your additional comments have also thrown some light on issues I wasn't aware of. So thanks again, your input has been very helpful and reassuring! :-) Rich From vinjvinj at gmail.com Thu Mar 23 14:30:16 2006 From: vinjvinj at gmail.com (vj) Date: 23 Mar 2006 11:30:16 -0800 Subject: How to find out the next Friday using RelativeDateTime In-Reply-To: References: <1143135433.419508.52850@z34g2000cwc.googlegroups.com> Message-ID: <1143142216.937726.202500@z34g2000cwc.googlegroups.com> I figured out how to do it. This does not work: delta = ReltaiveDateTime(days=0, weekday(mx.DateTime.Friday, 0)) But this works: delta = ReltaiveDateTime(days=+0, weekday(mx.DateTime.Friday, 0)) From fredrik at pythonware.com Wed Mar 29 06:26:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 29 Mar 2006 13:26:21 +0200 Subject: Doc suggestions (was: Why "class exceptions" are not deprecated?) References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com><1143070060.384366.25480@z34g2000cwc.googlegroups.com><1143574346.354680.136060@i39g2000cwa.googlegroups.com><34bb7f5b0603290047o21b9a1b7k64cdd206f604fc10@mail.gmail.com> Message-ID: >> (I'm actually tempted to just copy and paste each page from the >> tutorial into the current wiki but I'd hate for it all to be deleted >> after doing that). > > just do it! btw, one alternative could be to use an infogame site for this purpose: http://infogami.com this gives you revision history, a permissions system (limiting editing to registered users might be a good idea), comments, an associated blog, voting, feeds, change logs, etc. to convert the current tutorial to infogami-compatible markup, use this: http://www.aaronsw.com/2002/html2text/ From no-spam at no-spam-no-spam.com Sat Mar 11 10:23:38 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 11 Mar 2006 16:23:38 +0100 Subject: "RuntimeError: dictionary changed size during iteration" ; Good atomic copy operations? In-Reply-To: References: Message-ID: Felipe Almeida Lessa wrote: > Em S?b, 2006-03-11 ?s 12:49 +0100, robert escreveu: > >>Meanwhile I think this is a bug of cPickle.dump: It should use .keys() >>instead of free iteration internally, when pickling elementary dicts. >>I'd file a bug if no objection. > > > AFAICS, it's a problem with your code. You should lock your object while > using it. That's what Threading.Lock is supposed to work for. If you > want to use threads, you have to know in what parts of your code there > should be locks. 99.99% no. I would have to use a lock everywhere, where I add or remove something into a dict or list of the struct. Thats not the purpose of big thread locks. Such simple operations are already atomic by the definition of Python - and thanks to the global interpreter lock. (Otherwise I would leave the Python language, God beware ... :-) ) I'm of course aware, where to use locks for resons of the application. But this is an issue on Python level. And it can be solved gracly and simple in Python - I guess: If cPickle.dump (and maybe also copy/deepcopy?) is corrected to work atomic on dicts (use .keys()) and list-copies or locks python threads) the problem is solved gracely and generally. Robert From sullivanz.pku at gmail.com Wed Mar 29 03:25:34 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 29 Mar 2006 00:25:34 -0800 Subject: CGI redirection: let us discuss it further In-Reply-To: References: <1143480299.024145.272600@u72g2000cwu.googlegroups.com> <1143566506.253970.172230@z34g2000cwc.googlegroups.com> <1143570263.164844.129800@z34g2000cwc.googlegroups.com> Message-ID: <1143620734.711566.88760@v46g2000cwv.googlegroups.com> Well, in that case, the internal direction is just what I need. Thank you so much for help. From sybrenUSE at YOURthirdtower.com.imagination Fri Mar 3 04:22:59 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 3 Mar 2006 10:22:59 +0100 Subject: Convert dictionary to HTTP POST References: Message-ID: Laszlo Zsolt Nagy enlightened us with: > How can I convert a dictionary into a HTTP POST string? I have an > example below, but this is not working correctly for special > characters. (" ' and others). URL-quote it. > In other words, if I use "Bessy's cat" instead of "Bessy" then the > http server will parse that to "Bessy's cat" The HTTP server won't perform HTML-quoting out of thin air. > Probably the problem is that I should not use urllib.quote but > something else. URL-quoting is the right thing to do: In [1]: import urllib In [2]: urllib.quote("Bessy's cat") Out[2]: 'Bessy%27s%20cat' If you want to give yourself an example of how it's done, run a network sniffer and post something to a website. 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 paul at boddie.org.uk Sun Mar 12 17:32:57 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 12 Mar 2006 14:32:57 -0800 Subject: Cheese Shop: some history for the new-comers In-Reply-To: References: <44126523$0$1016$afc38c87@news.optusnet.com.au> <44141D59.6050806@pollenation.net> <1142178342.382120.236130@j33g2000cwa.googlegroups.com> <1142189668.450949.228210@e56g2000cwe.googlegroups.com> Message-ID: <1142202777.843532.326880@j52g2000cwj.googlegroups.com> Tim Parkin wrote: > > Still some work left cleaning up after the move to the new site but this > is going to be a priority very soon. Do you want me to include you on > any emails regarding this? I'll have a look into the site developer tools for python.org and see what I can contribute. Paul From joel.hedlund at gmail.com Fri Mar 10 07:19:27 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Fri, 10 Mar 2006 13:19:27 +0100 Subject: A bit OT: Python prompts display as nested mail quotes in Thunderbird In-Reply-To: References: Message-ID: > They already ARE "plain text" (I don't know of anyone submitting > MIME/HTML enhanced content on this group). I know. > it would mean all other quoted text would not look "quoted" in your reader. I.e. they would have '>' chars at line start. That is *excatly* what I want and what I asked in my post. I don't need colored lines in the margin to understand quotes. From sybrenUSE at YOURthirdtower.com.imagination Fri Mar 3 07:40:59 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 3 Mar 2006 13:40:59 +0100 Subject: object's list index References: <1141388967.849854.239830@z34g2000cwc.googlegroups.com> Message-ID: Iain King enlightened us with: > i = 0 > for object in list: > objectIndex = i > print objectIndex > i += 1 Why not: for index, object in enumerate(list): print index 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 rupole at hotmail.com Sat Mar 11 16:35:42 2006 From: rupole at hotmail.com (Roger Upole) Date: Sat, 11 Mar 2006 16:35:42 -0500 Subject: Attaching files in windows using Python. References: <1141749010.184737.155850@p10g2000cwp.googlegroups.com> <1141752053.029483.42540@p10g2000cwp.googlegroups.com> Message-ID: <1142112904_4332@sp6iad.superfeed.net> You might want to try using win32gui.GetOpenFileNameW. It uses keyword arguments and doesn't require that you build a struct yourself: win32gui.GetOpenFileNameW(File='myfile.txt', Filter='Texts and scripts\0*.txt;*.py\0Py stuff\0*.py\0') Roger "sri2097" wrote in message news:1141752053.029483.42540 at p10g2000cwp.googlegroups.com... > Hi all, > I have got this far till now - > > import win32gui, struct, array, string > > OFN_ALLOWMULTISELECT=0x00000200 > OFN_EXPLORER=0x00080000 > > def arrayToStrings(resultArray): > """return list-of-strings corresponding to a char array, > where each string is terminated by \000, and the whole > list by two adjacent \000 bytes > """ > astr=resultArray.tostring() > manyStrings=[] > # perhaps a loop of string.split would be faster... > while len(astr) and astr[0]!='\000': > i=astr.index('\000') > manyStrings.append(astr[:i]) > astr=astr[i+1:] > return manyStrings > > def szFrom(anarray): > """return the string-pointer (sz) corresponding to a char > array, 0 (null pointer) if no array > """ > if anarray: return anarray.buffer_info()[0] > else: return 0 > > def arrayFrom(astring,additional=0): > """return a char array built from a string, plus 0 > or more \000 bytes as filler > """ > if not astring: astring='' > return array.array('c',astring+additional*'\000') > > def arrayMulti(stringlist): > """return a char array built from many strings, each > separated by a \000 byte, and two \000's at the end > """ > return arrayFrom(string.join(stringlist,'\000'),2) > > def buildOfn(resultarray,filters=None,initdir=None,title=None, > multisel=1,oldlook=0): > """build an OPENFILENAME struct as a string, with several > options and a given result-array for the string[s] that > will result from the GetOpenFileName call > """ > flags=OFN_EXPLORER > if multisel: flags=flags|OFN_ALLOWMULTISELECT > if oldlook: flags=flags&~OFN_EXPLORER > szfile,maxfile=resultarray.buffer_info() > szfilter=szFrom(filters) > szinitdir=szFrom(initdir) > sztitle=szFrom(title) > return struct.pack( > "3i2P2iPiPi2PI2hPi2P", > 76, 0, 0, # size, owner-hwnd, hinstance > szfilter, 0, 0, 0, # filter, custom-filter, > max-cust-filter,filter-index > szfile, maxfile, # file, max-file > 0, 0, # file-title, max-file-title > szinitdir, sztitle, # initial-dir, dialog-title > flags, 0, 0, # flags, file-offset, file-extension > 0, # def-ext > 0, 0, 0) # cust-data, func-hook, template-name > > def openNames(forsave=0,filters=None,initdir=None,title=None, > initfile=None,multisel=1,oldlook=0): > """return a list of filenames for open or save, given > interactively by the user through a common-dialog; if > more than 1 string is returned, the first is the directory, > followed by the filenames. > """ > resultBuffer=arrayFrom(initfile,8192) > title=arrayFrom(title) > initdir=arrayFrom(initdir) > filters=arrayMulti(filters) > ofn=buildOfn(resultBuffer,filters,initdir,title,multisel,oldlook) > if forsave: isok=win32gui.GetSaveFileName(ofn) > else: isok=win32gui.GetOpenFileName(ofn) > if not isok: return [] > return arrayToStrings(resultBuffer) > > def _test(): > return openNames( > filters=('Texts and scripts','*.txt;*.py','Py stuff','*.py*') > ) > > if __name__=='__main__': > print _test() > > But hear the Dialogue_box stops and waits for the user to select a > file. But Since I have the entire path of the file, How do I pass it to > the file name to populate the box automatically instead of the user > manually selecting a file. > > Any further help will be appreciated. > ----== 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 johnjsal at NOSPAMgmail.com Fri Mar 24 14:44:17 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 24 Mar 2006 19:44:17 GMT Subject: a problem to solve In-Reply-To: <1143071664.377833.136660@z34g2000cwc.googlegroups.com> References: <5oiUf.1818$No6.41433@news.tufts.edu> <1143071664.377833.136660@z34g2000cwc.googlegroups.com> Message-ID: mensanator at aol.com wrote: > Then you'll want to represent the lights as a 20-bit binary number. > > Each bit position corresponds to 4 lamps I'm not sure I understand that. If I use a 20-bit number, wouldn't each bit correspond to a single light on each switch? What do you mean that each bit is 4 lamps? From webraviteja at gmail.com Mon Mar 6 23:02:39 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 6 Mar 2006 20:02:39 -0800 Subject: need a start point for wsdl In-Reply-To: <1141703014.199482.33860@i39g2000cwa.googlegroups.com> References: <1141703014.199482.33860@i39g2000cwa.googlegroups.com> Message-ID: <1141704159.501313.123680@i39g2000cwa.googlegroups.com> Everything you need. http://diveintopython.org/soap_web_services/index.html From siona at chiark.greenend.org.uk Tue Mar 28 11:32:29 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 28 Mar 2006 17:32:29 +0100 (BST) Subject: in-place string reversal References: <1143554931.104392.187480@i39g2000cwa.googlegroups.com> Message-ID: Felipe Almeida Lessa wrote: >Em Ter, 2006-03-28 ??s 16:03 +0100, Sion Arrowsmith escreveu: >> >>> "".join(reversed("foo")) >$ python2.4 -mtimeit '"".join(reversed("foo"))' >100000 loops, best of 3: 2.58 usec per loop But note that a significant chunk is the join(): $ python2.4 -mtimeit '"".join(reversed("foo"))' 100000 loops, best of 3: 2.72 usec per loop $ python2.4 -mtimeit 'reversed("foo")' 1000000 loops, best of 3: 1.69 usec per loop >$ python2.4 -mtimeit '"foo"[::-1]' >1000000 loops, best of 3: 0.516 usec per loop Yeah, I forget about [::-1] due to the high profile of the introduction of reversed(). Well, of sorted(), and reversed() coming along for the ride. And at some point reversed() will become a win: $ python2.4 -mtimeit 'reversed(range(200))' 100000 loops, best of 3: 6.65 usec per loop $ python2.4 -mtimeit 'range(200)[::-1]' 100000 loops, best of 3: 6.88 usec per loop -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From duncan.booth at invalid.invalid Thu Mar 30 02:16:59 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Mar 2006 07:16:59 GMT Subject: dynamic construction of variables / function names References: <1143701064.680576.285090@v46g2000cwv.googlegroups.com> Message-ID: Sakcee wrote: > python provides a great way of dynamically creating fuctions calls and > class names from string > > a function/class name can be stored as string and called/initilzed > > e.g > > def foo(a,b): > return a+b > > def blah(c,d): > return c*d > > > list = ["foo", "blah"] > > for func in list: > print func(2,4) > > or similar items No, that doesn't work. To convert a string to a function name you have to look it up in a suitable namespace, or store a list of functions instead of a list of strings. So something like this would work: lst = [foo, blah] for func in lst: print func(2,4) > > > what is the way if the names of functions are some modification e.g > > def Newfoo(a,b): > return a+b > > def Newblah(c,d): > return c*d > > list = ["foo", "blah"] > > for func in list: > print "New"+func(2,4) > > or define a variable > > "New"+list[0] = "First Funciton" > > > I think , print "New"+func(2,4) and "New"+list[0] = "First > Funciton" > > will not work, either eval or exec should be used > is it correct way, is there a simple way, is this techniqe has a name? > One common way is to group the functions you want callable together in a class and then use getattr to access them. class Commands: def Newfoo(self, a,b): return a+b def Newblah(self, c,d): return c*d def call(self, fname, *args. **kw): fn = getattr(self, "New"+fname) return fn(*args, **kw) cmds = Commands() lst = ["foo", "blah"] for func in lst: print cmds.call(func, 2, 4) From gdamjan at gmail.com Sat Mar 4 14:04:04 2006 From: gdamjan at gmail.com (Damjan) Date: 4 Mar 2006 11:04:04 -0800 Subject: Is there a WSGI sollutions repository somewhere Message-ID: <1141499044.178903.314840@j33g2000cwa.googlegroups.com> It seems that WSGI support starts to flourish is there some document or a web site that tracks what's out there, some place to pick and choose WSGI components? From me at privacy.net Mon Mar 20 20:59:47 2006 From: me at privacy.net (Dan Sommers) Date: Mon, 20 Mar 2006 20:59:47 -0500 Subject: Remote teamwork anecdotes (was: Where can we find top-notch python developers?) References: <1hceomq.1whcmq2114jly6N%aleaxit@yahoo.com> <2op3f3-uf6.ln1@lairds.us> Message-ID: On Tue, 21 Mar 2006 00:08:02 GMT, claird at lairds.us (Cameron Laird) wrote: > Briefly, remote collaboration works for me. I work on > customer premises part of the year, and, while there are > multipliers, my estimate is that they're far closer to > one than four. Sometimes they're less than one--I get > rather impatient with a lot of small talk, and locating > the approved meeting room, and waiting for approved > equipment, and ... > I like working with others, and sometimes indeed it's a > huge gain. Sometimes it's just noise. "We" (myself and at least one former coworker at a huge, multi-national, telecom company) noted that most software developers need both: Design meetings and similar almost have to be face to face. I can't draw and explain something on a white board *and* watch your reactions to it and to me over a telephone[1]. We also experienced failure modes during testing for which logs and bug reports and whatnot just aren't sufficient, but being in the same room as the person carrying out the test and pointing things out as the test fails can identify what's going on in seconds. OTOH, once the design is set, leave me alone and let me simulate it or code it, and maybe even get it past the first round of testing and tweaking/fixing. The last thing I want now is someone micro-managing and/or interrupting my every rinse, lather, repeat cycle. Regards, Dan [1] Last time I had the opportunity, which was back in 2001 or so, video conferences and "smart boards" didn't function as advertised. Color me skeptical. -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From onurb at xiludom.gro Thu Mar 2 08:39:43 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 02 Mar 2006 14:39:43 +0100 Subject: Is it better to use class variables or pass parameters? In-Reply-To: <1141241522.096240.53380@v46g2000cwv.googlegroups.com> References: <1141241522.096240.53380@v46g2000cwv.googlegroups.com> Message-ID: <4406f5c8$0$28950$626a54ce@news.free.fr> Derek Basch wrote: > This one has always bugged me. Is it better to just slap a "self" in > front of any variable that will be used by more than one class method s/class method/method/ In Python, a "class method" is a method working on the class itself (not on a given instance). > or should I pass around variable between the methods? One of the first rules I learned (from experience...) was to restrict as much as possible the scope of a variable. It usually makes code more readable, more robust, and more modular. In fact, I sometime even pass attributes of an object as args to a method of the same object, and/or assign values returned from a method of an object to attributes of the same object. This is more explicit than relying on side-effects. So (as pointed by almost everyone in this thread...) the best criteria here is : is this variable part of the state of an object, or is it just a value used for a given computation ? Note that if you find yourself passing the same huge set of variables from method to method for a given computation, this may calls for a refactoring... Python objects can be callable (ie function-like), so a complex computation with lot of shared state (independant from the rest of the object) may be best implemented as a separate temporary callable object - which can take the calling object as a parameter if it needs to access other attributes from it. 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 ahart at oneirasoft.com Mon Mar 13 14:10:27 2006 From: ahart at oneirasoft.com (ahart) Date: 13 Mar 2006 11:10:27 -0800 Subject: Which GUI toolkit is THE best? In-Reply-To: <441172c2$1@news1.ethz.ch> References: <441172c2$1@news1.ethz.ch> Message-ID: <1142277027.005336.170710@v46g2000cwv.googlegroups.com> i'm pretty much a newbie, too, and have been dabbling with some gui tools so far, i like pythoncard pretty well it wraps wxpython and seems to be pretty easy to use From jjl at pobox.com Thu Mar 30 18:42:07 2006 From: jjl at pobox.com (John J. Lee) Date: 30 Mar 2006 23:42:07 +0000 Subject: urllib2 through basic auth'ed proxy References: Message-ID: <87u09fxzxs.fsf@pobox.com> Alejandro Dubrovsky writes: [...] > How does one connect through a proxy which requires basic authorisation? > The following code, stolen from somewhere, fails with a 407: > [...code involving urllib2.ProxyBasicAuthHandler()...] > Can anyone explain me why this fails, or more importantly, code that would > work? OK, I finally installed squid and had a look at the urllib2 proxy basic auth support (which I've steered clear of for years despite doing quite a bit with urllib2). Seems quite broken. Appears to have been broken back in December 2004, with revision 38092 (note there's a little revision number oddness in the Python SVN repo, BTW: http://mail.python.org/pipermail/python-dev/2005-November/058269.html): --- urllib2.py (revision 38091) +++ urllib2.py (revision 38092) @@ -720,7 +720,10 @@ return self.retry_http_basic_auth(host, req, realm) def retry_http_basic_auth(self, host, req, realm): - user,pw = self.passwd.find_user_password(realm, host) + # TODO(jhylton): Remove the host argument? It depends on whether + # retry_http_basic_auth() is consider part of the public API. + # It probably is. + user, pw = self.passwd.find_user_password(realm, req.get_full_url()) if pw is not None: raw = "%s:%s" % (user, pw) ... That can't be right, can it? With a proxy, you're always authenticating yourself for the whole proxy, and you want to look up (RFC 2617 section 3.2.1). The ProxyBasicAuthHandler subclass dutifully passes in the right thing for the host argument, but AbstractBasicAuthHandler ignores it, which means that it never finds the password -- e.g. if you're trying to connect to python.org through myproxy.com, it'll be looking for a username/password for python.org instead of the needed myproxy.com. Obviously nobody else uses authenticating proxies either, or at least nobody who can be bothered to fix urllib2 :-( A workaround is to supply a stupid HTTPPasswordMgr that always returns the proxy credentials regardless of what the handler asks it for (only tested with a perhaps-broken 2.5 install, since I've broken my 2.4 install): import urllib2 class DumbProxyPasswordMgr: def __init__(self): self.user = self.passwd = None def add_password(self, realm, uri, user, passwd): self.user = user self.passwd = passwd def find_user_password(self, realm, authuri): return self.user, self.passwd proxy_auth_handler = urllib2.ProxyBasicAuthHandler(DumbProxyPasswordMgr()) proxy_handler = urllib2.ProxyHandler({"http": "http://localhost:3128"}) proxy_auth_handler.add_password(None, None, 'john', 'blah') opener = urllib2.build_opener(proxy_handler, proxy_auth_handler) f = opener.open('http://python.org/') print f.read() Yuck, yuck, yuck! I had realised the auth/proxies code in urllib2 was buggy, but... And all those hoops to jump through. Also, if you're using 2.5 SVN HEAD, it seems revision 42133 broke ProxyHandler in an attempt to fix the URL host:post syntax! I'll try to get some fixes in tomorrow so that 2.5 isn't broken (or at least flag the issues to let somebody else fix them), but no promises as usual... John From diffuser78 at gmail.com Fri Mar 10 09:30:02 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 10 Mar 2006 06:30:02 -0800 Subject: Python and C Message-ID: <1142001002.398147.199140@j52g2000cwj.googlegroups.com> I was a C Programmer for a while. Lately started to learn Python for one small project at school. I joined a small company where they use C++ for development. Can we use Python and C together ? I mean create some classes in Python and some number crunching algorithms coded in C (for speed) and integreate both of them. Could somebody just show a real small example or give pointers to the same. Thanks From invitro81 at gmx.net Fri Mar 10 07:36:18 2006 From: invitro81 at gmx.net (invitro81) Date: Fri, 10 Mar 2006 13:36:18 +0100 Subject: Which GUI toolkit is THE best? Message-ID: <441172c2$1@news1.ethz.ch> Hello I've recently learnt python and I do love it! I congratulate all those geeks who produce this nice language; well, because I could be called a nearby newbee I've decided to improve my abilities by writing my own nice editor with python; so I've to choose among all those GUI toolkit's available there.. But I've no idea which one I should use to start with.. I've read that tkinter seems to be the de facto standart in the pyhon community; but why? Is it the best available one or are theire other reasons? I read also a litte about wxpython and pygtk.. both are appealing to me but again to make a choice is difficult; is there also some guy liking pyqt is it worse or should it be avoided because of the licencing policy for qt (which I also like..)? * Which one is the most fun to program with? * Which one is the most easy to learn? * Which one looks best? * Which one is the most productive to program with? From python-url at phaseit.net Mon Mar 27 14:08:03 2006 From: python-url at phaseit.net (Peter Otten) Date: Mon, 27 Mar 2006 19:08:03 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 27) Message-ID: QOTW: "Testing real examples in doctstrings, or external documentation like tutorials, is important because it's very frustrating for people reading the docs if the examples don't work as advertised." - Marc Rintsch "If you don't document what the sundry variables are FOR, you're really not documenting your code at all -- just listing the names of some attributes is far too weak." - Alex Martelli If unittest is the standard way to write testing code, why do we still have doctest? Because serious testers use both. http://groups.google.com/group/comp.lang.python/browse_frm/thread/b49d428f5c47f728/9f2348ceaf88d5a5?tvc=1 Coincidentally, Terry Hancock dedicates a large portion of his report from PyCON 2006 to the power and simplicity of doctest. http://blog.freesoftwaremagazine.com/users/t.hancock/2006/03/18/title_3 Do you have any recipes that you find indispensable in your daily work but that are not obvious to a beginner? Contribute them to Aahz' collection. http://groups.google.com/group/comp.lang.python/browse_frm/thread/8b752d91a7b83140/3dee683b0daa700b?tvc=1 When using eval() is too dangerous you may still be able to facilitate Python's parsing infrastructure as Michael Spencer shows: http://groups.google.com/group/comp.lang.python/browse_frm/thread/789f2c8f7196e6e5/5c7a4f8438ec948c?tvc=1 Want to squeeze your precious unicode data into ASCII strings? FLundh's solution builds on character decomposition and unicode.translate()'s ability to replace one character with many. http://groups.google.com/group/comp.lang.python/msg/77196f64a90ea9bc Andrew Dalke explores the performance implications of various approaches to class instantiation and has collected a few quotes on the __slots__ feature. http://www.dalkescientific.com/writings/diary/archive/2006/03/19/class_instantiation_performance.html Andrew Clover has derived nice Windows Icons from the new Python logo. http://groups.google.com/group/comp.lang.python/msg/0ad44c95e81b93cb The mythical Python 3000 is mythical no more as you can watch it evolve on its own mailing list. Rumour has it that there is also a branch in subversion, only slighly obfuscated by its name. http://mail.python.org/pipermail/python-3000/2006-March/thread.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 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://python.sourceforge.net/peps/pep-0042.html 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 mitsura at skynet.be Tue Mar 14 04:08:27 2006 From: mitsura at skynet.be (mitsura at skynet.be) Date: 14 Mar 2006 01:08:27 -0800 Subject: wxPython Q? floating window Message-ID: <1142327307.197117.71320@i40g2000cwc.googlegroups.com> Hi, I have a question about wxPython. On Windows systems, you can point your mouse over most items on your desktop and a after a second or so, a small window will pop-up with extra info about the thing your pointing at (try e.g. move your mouse over the time in the right corner and a window will pop-up with the date). I was wondering this can be done with wxPython. I basically want to create a wxTree object and when I point the mouse over the objects in the tree I would like to have these kind of smal pop-up windows that display more info about the object you are pointing at. Any help much appreciated. Kris From apardon at forel.vub.ac.be Mon Mar 27 05:06:57 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 27 Mar 2006 10:06:57 GMT Subject: __slots__ References: <1143106365.996810.269780@z34g2000cwc.googlegroups.com> <1hcqwk5.9z7uv51pwbdrbN%aleaxit@yahoo.com> <1hcr1bw.1dywgpk1l0cpafN%aleaxit@yahoo.com> Message-ID: Op 2006-03-25, John J. Lee schreef : > aleaxit at yahoo.com (Alex Martelli) writes: > [...] >> you should be using pychecker or pylint > [...] > > I'm curious, as somebody who doesn't regularly use these tools: How do > they fit into your workflow? Do you run them every few hours, every > day, every time you run functional tests, every release, every so > often, on gut feeling about when it's likely to catch problems...? > > How do you cope with spurious warnings? Does it involve tweaking code > to quell warnings? Keeping suppression lists? Maintaining special > invocations of pychecker / pylint per-project? Do they cope well with > other people's code who do not use these tools? IMO they don't cope well unless you adapt to what they expect. I just tested the two. pylint gave me countless warnings because I use two space to indent instead of four. It also didn't like that I used uppercase letters in my identifiers. That there was no space after a comma or around an operator was a problem too. That I use the same name for the index variable of for loops in different scopes is also warned about. Pychecker also warns about these shadowed variable. Pychecker goes even so far to warn you that a local variable in an imported module is shadowing a global variable of yours. Like the following line: /usr/lib/python2.3/random.py:247: Local variable (i) shadows global defined on line 43 in file demo1a.py So it seems pychecker thinks I shouldn't use something like for i in lst: ... in my code at the global level because some module in the standard library has a function with a local i. Pychecker also froze on my system. I don't recommend the use of these tools. -- Antoon Pardon From johnjsal at NOSPAMgmail.com Tue Mar 7 10:14:06 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 07 Mar 2006 15:14:06 GMT Subject: raw strings and \ In-Reply-To: <1hbsqer.15chcl8img3bpN%aleaxit@yahoo.com> References: <1141548565.145199.145910@e56g2000cwe.googlegroups.com> <1141576051.081203.318010@e56g2000cwe.googlegroups.com> <1hbpy3y.23h9u0zn7y7zN%aleaxit@yahoo.com> <1141580623.066639.51160@u72g2000cwu.googlegroups.com> <1hbq3fx.2idn1u1cei6j0N%aleaxit@yahoo.com> <382Pf.1735$No6.40328@news.tufts.edu> <1hbsqer.15chcl8img3bpN%aleaxit@yahoo.com> Message-ID: <2rhPf.1736$No6.40369@news.tufts.edu> Alex Martelli wrote: > John Salerno wrote: > >> Alex Martelli wrote: >> >>>> Now get back to work on your new Nutshell book :-) >>> Yep, good point!-) >> Are you working on a new edition? I didn't see any new Python books >> listed on O'Reilly's site through April, but I'd definitely be >> interested in new versions of the books I plan to get soon (Cookbook and >> Nutshell, for example, although I figure the Cookbook is fairly new at >> this point.) > > Yep, a 3rd edition of the Cookbook is not in the cards. A 2nd edition > of the Nutshell is, and if all goes well should be out before the fall. > > > Alex Awesome, can't wait! :) From steve at holdenweb.com Sun Mar 12 13:32:48 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Mar 2006 18:32:48 +0000 Subject: Cheese Shop -> BSOL? In-Reply-To: <6a246d8e0603112325p251ebb3ep7f09c1e1d9446964@mail.gmail.com> References: <6a246d8e0603112325p251ebb3ep7f09c1e1d9446964@mail.gmail.com> Message-ID: Bertrand Mansion wrote: > On 3/12/06, Andrew Gwozdziewycz wrote: > >>Look at the 'tadpoles' (i don't really think it's tadpoles really... >>but i'll bite for now), >>notice that it is a + sign, which we also always associate with life, >>and health (red cross comes to mind). Python >>is a healthy language. I can read it and write it without going blind >>or crazy. > > > The cross, the snake and the S shape are indeed very commonly > associated with a medical universe. The current logo would be perfect > for a drug company. > > >> >Better eggs.python.org. Would support the spread of the new file >> >format, too. >> >>eggs.python.org actually seems quite good to me. It'd be even cooler >>if we could make EGGS an acronym for something. >>How about 'Excellently Good Getting Solution' ? (joking). > > > +1 for eggs.python.org > eggs: Easily Get Good Stuff? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From ziga.seilnacht at gmail.com Tue Mar 14 12:45:08 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 14 Mar 2006 09:45:08 -0800 Subject: Trace dynamically compiled code? References: Message-ID: <1142358308.322866.284290@z34g2000cwc.googlegroups.com> Ed Leafe wrote: > Hi, > > Thanks to the help of many on this list, I've been able to take code > that is created by the user in my app and add it to an object as an > instance method. The technique used is roughly: Just some notes about your code: > nm = "myMethod" > code = """def myMethod(self): > print "Line 1" > print "My Value is %s" % self.Value > return > """ > compCode = compile(code, "", "exec") > exec compCode Try not using bare exec statements, since they pollute the local scope. In your example you could use: compCode = compile(code, "", "exec") d = {} exec compCode in d func = d[nm] See http://docs.python.org/ref/exec.html for details. > exec "self.%s = %s.__get__(self)" % (nm, nm) You don't need dynamic execution here; you can simply use setattr and the new module: import new method = new.instancemethod(func, self) setattr(self, nm, method) and yes, I remember that I was the one who suggested you the __get__ hack. > This is working great, but now I'm wondering if there is a way to > enable pdb tracing of the code as it executes? When tracing "normal" > code, pdb will show you the name of the script being executed, the > line number and the source code for the line about to be executed. > But when stepping through code compiled dynamically as above, the > current line's source code is not available to pdb, and thus does not > display. > > Does anyone know a way to compile the dynamic code so that pdb can > 'see' the source? I suppose I could write it all out to a bunch of > temp files, but that would be terribly messy. Are there any neater > solutions? You should check py lib: http://codespeak.net/py/current/doc/ , specifically the py.code "module". Then you can modify the function from above: import inspect f = inspect.currentframe() lineno = f.f_lineno - 5 # or some other constant filename = f.f_code.co_filename import py co = py.code.Code(func) new_code = co.new(co_lineno=lineno, co_filename=filename) new_func = new.function(new_code, func.func_globals, nm, func.func_defaults, func.func_closure) > -- Ed Leafe > -- http://leafe.com > -- http://dabodev.com Ziga Seilnacht From deets at nospam.web.de Fri Mar 10 09:37:41 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 10 Mar 2006 15:37:41 +0100 Subject: Python and C References: <1142001002.398147.199140@j52g2000cwj.googlegroups.com> <47dhb9Fep4siU1@uni-berlin.de> Message-ID: <47dhctFep4siU2@uni-berlin.de> > http://docs.python.org/api/api.html That should have been http://docs.python.org/ext/ext.html but you need the other one sooner or later. Diez From jstucklex at attglobal.net Sat Mar 25 16:41:30 2006 From: jstucklex at attglobal.net (Jerry Stuckle) Date: Sat, 25 Mar 2006 16:41:30 -0500 Subject: HIRING: PHP Developer In-Reply-To: <1143313877.802242.206050@i40g2000cwc.googlegroups.com> References: <1143313877.802242.206050@i40g2000cwc.googlegroups.com> Message-ID: HiringDivision at gmail.com wrote: > From: In Need - view profile > Date: Fri, Mar 24 2006 10:39 pm > Email: "In Need" > Groups: hfx.forsale > Not yet ratedRating: > show options > > > Reply | Reply to Author | Forward | Print | Individual Message | Show > original | Report Abuse | Find messages by this author > > > We are hiring a PHP developer! > > The site must contain the following: > - database > - administrator panel (implementing multiple employee logins / > permissions) > - credit card / paypal processing > - affiliate program > - news scripting control panel > - image design > - coupons / discounts, & gift certificates > - customer log in / log out > - specials page > - contests > - forum > > > Would like to have: > - flash design > - various language support > - pages that have pre-loaded data (click the link and no new page opens > > within the main frame. Simply brings the information forward). > > > The individual(s) that are selected for this project will have the > opportunity to remain our company's web and image designer(s). Please > send > a price quote for the above mentioned request, as well as a quote for a > > design similar to www.IGE.com to HiringDivision at gmail.com. > > > Thank you. > I want to buy a car. It must seat four people and be read. Please send quote. That's basically what you're asking for. No way would I ever make a quote to do a project based on this information. However, I can quote you an hourly rate for the design you can use to get a quote. -- ================== Remove the "x" from my email address Jerry Stuckle JDS Computer Training Corp. jstucklex at attglobal.net ================== From onurb at xiludom.gro Tue Mar 21 06:17:13 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 21 Mar 2006 12:17:13 +0100 Subject: should os.walk return a list instead of a tuple? In-Reply-To: References: Message-ID: <441fe0f3$0$27072$626a54ce@news.free.fr> Ministeyr wrote: > Hello, > > os.walk doc: http://www.python.org/doc/2.4/lib/os-file-dir.html#l2h-1625 > > When walking top to bottom, it allows you to choose the directories you > want to visit dynamically by changing the second parameter of the tuple > (a list of directories). However, since it is a tuple, you cannot use > "filter" on it, since it would mean reassigning it: > > for dir_tuple in os.walk('/home'): > dir_tuple[1]=filter(lambda x: not x.startswith('.'), > dir_tuple[1]) #do not show hidden files > print dir_tuple #just print the directory and its contents in > the simplest possible way Ok, you are missing 2 points here : 1/ multiple assignment. Python allows you to do things like: a, b, c = (1, 2, 3) So the canonical use of os.walk is: for dirpath, subdirs, files in os.walk(path): ... 2/ what's mutable and what is not: a tuple is immutable, but a list is not. The fact that the list is actually an element of a tuple doesn't make it immutable: >>> t = ('A', [1, 2, 3]) >>> t ('A', [1, 2, 3]) >>> t[1] [1, 2, 3] >>> # this will work >>> t[1].append(4) >>> t ('A', [1, 2, 3, 4]) >>> # this won't work >>> t[1] = [] Traceback (most recent call last): File "", line 1, in ? TypeError: object does not support item 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 ed at leafe.com Tue Mar 14 08:45:05 2006 From: ed at leafe.com (Ed Leafe) Date: Tue, 14 Mar 2006 08:45:05 -0500 Subject: Trace dynamically compiled code? Message-ID: <6A65F4A4-DC66-46E2-B2EB-3BB50DCE2856@leafe.com> Hi, Thanks to the help of many on this list, I've been able to take code that is created by the user in my app and add it to an object as an instance method. The technique used is roughly: nm = "myMethod" code = """def myMethod(self): print "Line 1" print "My Value is %s" % self.Value return """ compCode = compile(code, "", "exec") exec compCode exec "self.%s = %s.__get__(self)" % (nm, nm) This is working great, but now I'm wondering if there is a way to enable pdb tracing of the code as it executes? When tracing "normal" code, pdb will show you the name of the script being executed, the line number and the source code for the line about to be executed. But when stepping through code compiled dynamically as above, the current line's source code is not available to pdb, and thus does not display. Does anyone know a way to compile the dynamic code so that pdb can 'see' the source? I suppose I could write it all out to a bunch of temp files, but that would be terribly messy. Are there any neater solutions? -- Ed Leafe -- http://leafe.com -- http://dabodev.com From linuxnooby at yahoo.com.au Fri Mar 17 21:04:53 2006 From: linuxnooby at yahoo.com.au (linuxnooby at yahoo.com.au) Date: 17 Mar 2006 18:04:53 -0800 Subject: message box halts prgram flow Message-ID: <1142647493.427513.73170@z34g2000cwc.googlegroups.com> HI I am creating a tkinter app. example tkMessageBox.showinfo("Window Text", "A short message") print "blah" The execution of the application halts when the message box is displayed until the user clicks OK, then "blah is printed. However I want the program to display message box and continue on to print blah without waiting for user response. Any suggestions on how to go about this? cheers David From erniedude at gmail.com Wed Mar 29 14:17:49 2006 From: erniedude at gmail.com (Ernesto) Date: 29 Mar 2006 11:17:49 -0800 Subject: Terminating a subprocess question In-Reply-To: References: <1143649900.667952.15410@t31g2000cwb.googlegroups.com> <1143654541.198515.62520@z34g2000cwc.googlegroups.com> Message-ID: <1143659869.340205.289790@j33g2000cwa.googlegroups.com> Fredrik Lundh wrote: > Ernesto wrote: > > > Plus, everytime, I tried to use the read_all object, my program crashed > > pretty hard... > > > > tn = telnetlib.Telnet("localhost",6000) > > print tn.read_all() > > # CRASH > > that's an unusual error message. are you sure you didn't get a > traceback? if so, what did it say? > > I was running it directly in a python shell. After the tn.read_all() call, the python shell window freezes up, and I have to do a hard termination of the shell. There is no traceback message, just a freeze. From smritibhagat at gmail.com Fri Mar 17 20:47:00 2006 From: smritibhagat at gmail.com (smritibhagat at gmail.com) Date: 17 Mar 2006 17:47:00 -0800 Subject: SVD question In-Reply-To: References: <1142643103.099002.284190@p10g2000cwp.googlegroups.com> Message-ID: <1142646420.653357.243510@i40g2000cwc.googlegroups.com> Hi Robert! Oh! Its not a homework problem... I read the Golub book, it tells me what an orthogonal complement is, however, I cannot understand how I can code it. I know about svd from numpy's mlab, but I what I want to know is how can I compute an orthogonal complement, using SVD or otherwise. Thanks for the prompt reply :) From jgardner at jonathangardner.net Tue Mar 21 19:43:41 2006 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: 21 Mar 2006 16:43:41 -0800 Subject: Using Dictionaries in Sets - dict objects are unhashable? In-Reply-To: References: Message-ID: <1142988221.350758.316400@i39g2000cwa.googlegroups.com> Welcome to Python, where all types are either static (and thus hashable) or volatile (and thus not hashable.) The way hash tables work (which is what powers the set and dict types), you have to be able to get a number from an instance of the type, with the following conditions true: (1) Every equivalent instance (whatever that means to you) will give you the same number for the type. (2) You always get the same number for the instance of the type. (Because things should be equal to themselves.) If these two things don't hold true, then the hash tables won't work like you would expect them to. (Imagine punching in the same dict that has been modified slightly as the key. What do you expect to get back?) You *could* create a dict that hashes off of its unique id. But the id isn't really unique because old ids get recycled. You *could* convert the dict to a tuple of key-value pairs, and then hash that, but every value in that tuple would have to be hashable. Instead of storing the dicts in the set, trying storing something else that is hashable, and invent some way of "remembering" which thing refers to which dict. From jhefferon at smcvt.edu Fri Mar 10 07:38:56 2006 From: jhefferon at smcvt.edu (Jim) Date: 10 Mar 2006 04:38:56 -0800 Subject: A better RE? In-Reply-To: References: Message-ID: <1141994336.538970.162480@i39g2000cwa.googlegroups.com> Eddie Corns wrote: > Just a small point - what does "in order" mean here? if it means that eg 1362 > is not valid then you're stuck because it's context sensitive and hence not > regular. I'm not seeing that. Any finite language is regular -- as a last resort you could list all ascending sequences of 7 or fewer digits (but perhaps I misunderstood the original poster's requirements). Jim From riko at despammed.com Wed Mar 1 14:41:21 2006 From: riko at despammed.com (Mc Osten) Date: Wed, 1 Mar 2006 20:41:21 +0100 Subject: Path completion in 'raw-input'? References: Message-ID: <1gzqkupj75iyd.dlg@rikodespammed.com> On Wed, 01 Mar 2006 10:00:43 -0800, Johannes Graumann wrote: > There's also the rlcompleter module, but in the interest of better platform > agnosis I'd like to stick with cmd ... I would have suggested readline.. This works on Windows: This about readline on MacOS: [ you don't need if you use Python 2.4 from undefined.org ] -- USB Priests for only 10$ From nemesis at nowhere.invalid Sat Mar 18 03:59:29 2006 From: nemesis at nowhere.invalid (Nemesis) Date: Sat, 18 Mar 2006 08:59:29 GMT Subject: Xah's Edu Corner: The Concepts and Confusions of Pre-fix, In-fix, Post-fix and Fully Functional Notations References: <1142490052.127055.50130@v46g2000cwv.googlegroups.com> <1142585935.934786.115700@e56g2000cwe.googlegroups.com> Message-ID: <20060318082708.2270.10480.XPN@orion.homeinvalid> Mentre io pensavo ad una intro simpatica "Roedy Green" scriveva: >>Hmmm... it displays fine via google groups. Maybe it's the reader which >>is 'non-compliant' ? > I am using Agent. You configure your database with an encoding, > which is by default the platform encoding, not UTF-8. I have just > flipped it over to UTF-8. We'll see if that makes Xah's future UTF-8 > messages more readable. Agent uses this 'charset' to decode articles with no 'charset' declared. In the OP article the charset is correctly declared so Agent should decode it without problems ... perhaps your Agent is not configured in the right way, maybe you are forcing it to use your charset instead of the declared one. -- Do not attempt to traverse a chasm in two leaps. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From justin.frost at gmail.com Fri Mar 10 11:56:52 2006 From: justin.frost at gmail.com (MakaMaka) Date: 10 Mar 2006 08:56:52 -0800 Subject: creating variable in root namespace from module In-Reply-To: References: <1141976796.594066.229210@e56g2000cwe.googlegroups.com> Message-ID: <1142009812.786850.218860@z34g2000cwc.googlegroups.com> Hi again, Steve- I'm trying to use python to model reliability. Basically, I want to read an XML file in that defines a bunch of variables, that are then accessible from the python interpreter. For example: import reliability reliability.read_xml("c:\\somefile.xml") #<== defines x1, x2, x3 result = x1+x2+x3 This tool will be used by people who are not necessarily coders and I don't want them to have to deal with passing global namespaces etc. Duncan- I like your idea; however, I don't want the user to actually have to know the structure of the xml file, so I don't think I can do it this way. There might be 3, 4 or 1000 variables that the function needs to create. Any other ideas? What clever technical ways have been used? I know I can just have the function add the variables to the global namespace of the module and then access them like reliability.x1 or in a dict or something, but I think this might confuse some of my potential users who aren't familiar with Object Oriented programming (think electrical engineers who still code in Fortran). Thanks, Justin From struggleyb at gmail.com Sat Mar 4 10:37:15 2006 From: struggleyb at gmail.com (Bo Yang) Date: Sat, 04 Mar 2006 23:37:15 +0800 Subject: do design patterns still apply with Python? In-Reply-To: <21d803730603040619k22d04938i935118f1226e12b@mail.gmail.com> References: <8SINf.1718$No6.40137@news.tufts.edu> <7x8xrs9xqb.fsf@ruckus.brouhaha.com> <7xirqwz5ye.fsf@ruckus.brouhaha.com> <1141381499.859849.85900@p10g2000cwp.googlegroups.com> <7xk6bamxwo.fsf@ruckus.brouhaha.com> <21d803730603040619k22d04938i935118f1226e12b@mail.gmail.com> Message-ID: <4409B42B.1050003@gmail.com> Paul Novak : > A lot of the complexity of design patterns in Java falls away in > Python, mainly because of the flexibility you get with dynamic typing. > I agree with this very much ! In java or C++ or all such static typing and compiled languages , the type is fixed on in the compile phrase , so for the flexible at the runtime , we often need to program to interface . For example , we do in java : implement I{...} class A implement I{...} class B implement I{...} oprate(I var) // we can pass A's instance or B's instance here and in C++ : class Abstract{...} class A : Abstract{...} class B : Abstract{...} oprate(Abstract var) // pass the A's instance or B's instance here But in python , type is dynamic , and name is bind at runtime , so we can pass any variable as we want ! This feather make python not need for redundant class inherits and interfaces which are the core of the GoF's design patterns I think ! > For a Pythonic Perspective on Patterns, "Python Programming Patterns" > by Thomas W. Christopher is definitely worth tracking down. It looks > like it is out of print, but you can find used copies on Amazon. > > Regards, > > Paul. > > > > This sounds like an article crying out to be written, > "(Learning) Design Patterns with Python". > > Has it been written already? > > Cheers, > Terry > > > Bruce Eckel began writing "Thinking In Python" it was last updated > in 2001. > From kent at kentsjohnson.com Mon Mar 6 20:39:33 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 06 Mar 2006 20:39:33 -0500 Subject: Is this not infinite? In-Reply-To: References: Message-ID: <440cdf90$1_2@newspeer2.tds.net> John Salerno wrote: > From a book: > > class Derived(Base): > def __init__(self, etc....): > self.__init__(self, etc...) This should be def __init__(self, etc....): Base.__init__(self, etc...) or possibly def __init__(self, etc....): super(Derived, self).__init__(etc...) > Obviously I'm missing a piece of information that would help me to see > why the call gets passed back up to Base... It's a typo in the book. Kent From skip at pobox.com Sun Mar 19 18:19:12 2006 From: skip at pobox.com (skip at pobox.com) Date: Sun, 19 Mar 2006 17:19:12 -0600 Subject: cmp() on integers - is there guarantee of returning only +-1 or 0? In-Reply-To: <441dd94c$0$20108$834e42db@reader.greatnowhere.com> References: <441dd94c$0$20108$834e42db@reader.greatnowhere.com> Message-ID: <17437.59120.525541.916421@montanaro.dyndns.org> Dmitry> doc says that it must be > 0, or < 0, but it seems that it Dmitry> returns +1 or -1. Can it be reliably used to get the sign of x: Dmitry> cmp(x, 0) like pascal Sign() function does? Why not def sign(n): return n and n/abs(n) or 0 Skip From paul at boddie.org.uk Sat Mar 18 12:57:38 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 18 Mar 2006 09:57:38 -0800 Subject: How to run SimpleHTTPServer on IronPython on Mono References: Message-ID: <1142704658.119938.20480@e56g2000cwe.googlegroups.com> Sanghyeon Seo wrote: > I took some time to write this HOWTO: > http://sparcs.kaist.ac.kr/~tinuviel/fepy/howto/simplehttpserver-ironpython-mono-howto.html Thanks for spending the time writing this. Whilst I don't run Mono or anything similar, new Python documentation is surely a welcome thing. > IronPython seems to get much less interest than it deserves. [...] > The purpose of this document is twofold: to show how to run > SimpleHTTPServer on IronPython on Mono, and to debunk some myths like: > > * IronPython doesn't run on Mono But it does require recent versions, according to the document. Requiring the latest stuff straight from the revision control repository is always an inhibiting factor in the adoption of software. > * IronPython doesn't support Python standard library > * IronPython is a toy I don't think people really believe either of these any more. However, the IronPython developers haven't really done a good job at explaining the benefits of their work, or clearing up potential misconceptions. For example, take a look at the previously-promoted Web site: http://www.ironpython.com It's out-of-date and doesn't mention the current Web site, which is a mere section of some corporate "community" site for .NET: hardly a good way of promoting something with (potential for) a fairly decent brand identity. Then, consider the licensing situation: whilst IronPython appears to have a fairly permissive licence [1], Microsoft have decided to put it under their "shared source" umbrella [2], confusing things substantially, since that label used to mean that you could conditionally look at Microsoft's code but do little else with it; even now they promote three licences, one of which being similar but not exactly the same as the "Shared Source License for IronPython". With various existing open source licences, particularly the Free Software licences, you know where you stand almost straight away. Meanwhile, confusing, marketing-directed labelling only makes people less certain about what they're getting into and what's being hidden from them. However, one benefit of Microsoft's desire to simplify their licensing is that the resulting compatibility with existing licences has had some tentative recognition [3]. Finally, there's the issue of the platform. I imagine that many people regard the debate as being over as to whether Mono and other similar projects independent of Microsoft are genuinely open, now that various Free Software-oriented GNU/Linux distributions are planning to distribute Mono, but the Mono developers don't score any publicity points for having belittled some fairly legitimate concerns about things like patent claims related to the various "standards" involved. For what it's worth, nagging concerns about the Java platform's openness (especially related to the add-on standards like J2EE) still linger in the open source community. One other thing, not any fault of the IronPython developers themselves: I guess it doesn't help that the canonical implementation of Python - CPython - keeps growing new features which have already left Jython struggling to catch up. If IronPython users consider themselves to be part of the wider Python community, is it a good thing that they're reliant on Microsoft to keep that community from fragmenting? Paul [1] http://lists.debian.org/debian-legal/2005/08/msg00089.html [2] http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx [3] http://mail.fsfeurope.org/pipermail/press-release/2005q4/000120.html From sathyaish at gmail.com Mon Mar 13 06:01:47 2006 From: sathyaish at gmail.com (Sathyaish) Date: 13 Mar 2006 03:01:47 -0800 Subject: Environmental Variables In-Reply-To: References: <1142246053.485766.41280@i39g2000cwa.googlegroups.com> Message-ID: <1142247707.381011.154410@i39g2000cwa.googlegroups.com> Thanks for the replies. I am trying to have a startup file execute everytime I launch the interpreter. So, for a test, I wrote a small file I called "Sathyaish.py". The contents of the file were simply: # ! This is my new start-up file. print "Sathyaish is the best." Then, in the interpreter, on its prompt, I said: >>> os.environ['PYTHONSTARTUP'] = 'C:\\Sathyaish.py' >>> It didn't complain. I tested it immediately. On the same interpreter instance, I said: >>> import os >>> os.environ.get('PYTHONSTARTUP') It gave me back 'C:\Sathyaish.py'. I didn't close that interpreter. I left it open and launched a new instance of the interpreter. In this I queried the same: >>> import os >>> os.environ.get('PYTHONSTARTUP') None was what I got. I checked the at DOS prompt (cmd) for PYTHONSTARTUP, and I got an 'unrecognized program/command/batch file' interrupt. What's the deal with environmental variables? Are they specific to an interpreter session? That shouldn't be. From pydecker at gmail.com Sun Mar 12 10:52:02 2006 From: pydecker at gmail.com (Peter Decker) Date: Sun, 12 Mar 2006 10:52:02 -0500 Subject: Cheese Shop: some history for the new-comers In-Reply-To: References: <44126523$0$1016$afc38c87@news.optusnet.com.au> <44141D59.6050806@pollenation.net> <4414234F.7020605@pollenation.net> <44142CAA.9080407@pollenation.net> Message-ID: On 3/12/06, Fredrik Lundh wrote: > Peter Decker wrote: > > > I consider myself a Python developer, and if I saw a 'Developers' link > > on a Python site, it would seem obvious that it would be something > > that might interest me. > > even when it appeared below News, Documentation, Download, > Community, and Links buttons on a site dedicated to the Python > programming language ? > > who would you, intuitively, think that the other buttons were tar- > geted for ? I would expect 'Documentation' would lead to docs about *using* Python, not about the nuts and bolts that go into enabling Python to do its magic. Similarly, I would expect 'News' to be news that would be relevant to the users of the language, 'Community' to be about the community of people who use Python, etc. The number of people who could potentially be Python developers is immense compared to the number who will ever look at the source code behind it, much less tinker with it. > (and why wouldn't the development process behind Python be > of interest to you, btw? Probably because I have other work to do, and I use Python as the tool to get that work done. If I were a baker, I would be preoccupied with keeping my bakery in business; I wouldn't be spending much time studying flour mills or wheat farming, even though those endeavors make my bakery possible. > don't tell me that you've never dis- > covered a bug in Python or its documentation... ;-) Can't say I've ever run into anything that hadn't already been reported. But even if I did, my C skills are nowhere near good enough to be able to delve into the source code and correct it. That doesn't make me any less of a Python developer, though. -- # p.d. From dananrg at yahoo.com Tue Mar 7 16:29:08 2006 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: 7 Mar 2006 13:29:08 -0800 Subject: ODBC module and strange date reference <...> References: <1141294036.353794.211450@i39g2000cwa.googlegroups.com> Message-ID: <1141766947.945596.180030@j52g2000cwj.googlegroups.com> Magnus Lycka wrote: > Are you using an old version of ESRI software, or are > they shipping a product with an ancient version of Python? We're using the latest and greatest ArcGIS Desktop product, which is at release 9.1. Evidently they chose to use Python 2.1 to ensure a "silent install" when ArcGIS Desktop gets installed. I've been told the beta for ArcGIS Desktop 9.2 ships with Python 2.4, so it's safe to say the official release of 9.2 this summer will ship with Python 2.4 as well. At least that's my hope. > You can't really expect that third party product will > support Python 2.1 any longer. A lot of new software > take advantage of the new features in Python that came > in later versions. Current Python versions are also a > bit faster. I'm all for using for the latest version of Python. I'm just now learning about Python classes, and it seems like there were some significant changes at 2.2. > If I were you, I'd check with ESRI support if you can't > use a newer version of Python. I think it's possible. I think it is as well and am looking into it. Thanks again for your help Magnus. Dana From aleaxit at yahoo.com Sat Mar 25 12:35:31 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Mar 2006 09:35:31 -0800 Subject: Python types References: <1143230541.717833.35440@e56g2000cwe.googlegroups.com> <44247674$0$25385$636a55ce@news.free.fr> <1143306481.966061.26300@t31g2000cwb.googlegroups.com> Message-ID: <1hcr0pr.v4grs1tlhti8N%aleaxit@yahoo.com> Salvatore wrote: > Thank's everybody :-) > > > Here is a type d?finition I've found on the net which I agree with : > > Attribute of a variable which determines the set of the values this > variabe can take and the > operations we can apply on it. Hmmm -- that doesn't work very well for languages in which "a variable" is just "a name", because we cannot apply any operations at all on THE NAME -- we apply operations on the OBJECT to which the name refer. This issue arises with both languages where names "can take" any object, like Python, and ones where the compiler infers the subset (type) of objects that each name "can take", like Boo. Moreover, asserting that 'type' is an attribute of a variable means, for example, that a function's return-value, not being a variable, has no type -- that really makes no sense. And similarly for other expressions; e.g., consider, in Java, something like...: ( (Fooable) zip() ).getFoo() + ( (Barable) zop() ).getBar() no variables in sight, yet a lot of types in Java's normal sense -- the types of whatever objects zip() and zop() return, the (Fooable and Barable, respectively) types after the cast, the type of whatever getFoo and getBar return, and the type of their sum... Saying that an _object_ has a type thus makes more sense (even in Java and similar languages) than considering type to be an "attribute of a variable" -- *in addition* to objects, which have types, other language constructs, depending on the language, may or may not be imbued with type-constraints, be that declaratively (as, say, in Java), by compiler inference (as, say, in Boo), or by other means yet such as stropping (e.g., in Perl, you can tell from just looking at the name whether a variable refers to a scalar, $something, an array, @something, or a hash, %something -- in Python, Java or Boo you can't tell from just the name, but rather must find a declaration [Java], assignment [Python] or use [Boo] to let you read or infer the "scalar vs array" type issue). Alex From theller at python.net Wed Mar 29 12:39:11 2006 From: theller at python.net (Thomas Heller) Date: Wed, 29 Mar 2006 19:39:11 +0200 Subject: ctypes/libffi for Intel based Macintosh In-Reply-To: References: Message-ID: philip.kania at kodak.com wrote: > Can someone tell me where I can download a version of ctypes/libffi that > will work on a Intel based Macintosh? > > I'm running Mac OS X 10.4.5 and the ActiveState Python 2.4.2 distribution. > > I've tried building libffi 1.20 which came with ctypes 0.9.9.3 and got a > message from the libffi configure script that said libffi has not been > ported to i686-apple-darwin8.5.1. > I know that the PyObjC people have got libffi (they have their own version in CVS) working on an Intel-based Mac. Since I don't have access to such a machine, I have now way to port ctypes myself (hint, hint ;-). OTOH, the current way to go would be to build universal binaries, but I have even less clue how to do *that*. Thomas From joel.hedlund at gmail.com Wed Mar 29 02:44:44 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Wed, 29 Mar 2006 09:44:44 +0200 Subject: Difference between 'is' and '==' In-Reply-To: References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <4427d287$0$38669$edfadb0f@dread12.news.tele.dk> Message-ID: > If it weren't for the current CPython optimization (caching small > integers) This has already been covered elsewhere in this thread. Read up on it. > this code which it appears you would support writing > > if (flags & os.R_OK) is os.R_OK: I do not. You compare a module.CONSTANT to the result of an expression (flags & os.R_OK). Expressions are not names bound to objects, the identity of which is what I'm talking about. This example does not apply. Also, the identity check in my example has a value equality fallback. Yours doesn't, so it really does not apply. > (I think you should give it up... you're trying to push a rope.) I'm not pushing anything. I just don't like being misquoted. Cheers, Joel Hedlund From onurb at xiludom.gro Thu Mar 9 04:07:58 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 09 Mar 2006 10:07:58 +0100 Subject: Simple questions on use of objects (probably faq) In-Reply-To: References: <440ed33e$0$8002$636a55ce@news.free.fr> Message-ID: <440ff09d$0$20266$626a54ce@news.free.fr> Brian Elmegaard wrote: > bruno at modulix writes: > > >>Now how you could do it the OO way (Q&D, not really tested): > > > Something goes wrong in my 2.3 So it's time to move to 2.4x !-) What is "going wrong" exactly ? > when I change the syntax to > _add_instance=classmethod(_add_instance). > If I understand this correctly the class is keeping track of the > instances of itself. Yeps. > The class is extendible and has all the needed > methods. This means that any global lists can be > avoided. Yeps too. This is called "encapsulation". But this also means you only have one list of instances - which may or may not be ok for what you're trying to do. Note that there are possible workarounds, like using a dict of lists: class Foo(object): _instance_lists = {} def __init__(self, x, list_id): self.x = x # no, you won't avoid it self._add_instance(self, list_id) @classmethod def _add_instance(cls, instance, list_id): cls._instance_lists.setdefault(list_id, []).append(instance) @classmethod def get_instances(cls, list_id): return cls._instance_lists[list_id].[:] # now you need to add the list_id parameter to all others classmethods Also, if you intend to use such a solution (with or without multiple lists), you may want to add a classmethod to delete instances from the list(s). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From gregpinero at gmail.com Wed Mar 8 12:52:04 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Wed, 8 Mar 2006 12:52:04 -0500 Subject: How To Request Delivery Receipts On Emails Message-ID: <312cfe2b0603080952r419b843u3c9a0cc8d58a6b0@mail.gmail.com> Hi Guys, Does anyone know how to program a Python script to send out emails with a request delivery receipt? Is it something I can build into the email message via the mime stuff? And yes, I know it's probably a bad idea, but I can't talk my clients out of it ;-) -- Gregory Pi?ero Chief Innovation Officer Blended Technologies (www.blendedtechnologies.com) From grflanagan at yahoo.co.uk Sat Mar 4 15:25:14 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 4 Mar 2006 12:25:14 -0800 Subject: how to record how long i use the intenet In-Reply-To: <1141500107.245806.276530@v46g2000cwv.googlegroups.com> References: <1141500107.245806.276530@v46g2000cwv.googlegroups.com> Message-ID: <1141503914.680065.129060@e56g2000cwe.googlegroups.com> b53444 at gmail.com wrote: > use python > use ADSL > use windows XP > i want to record the time when i get on the internet and off the > internet > into a txt file > HOW? http://en.wikipedia.org/wiki/Water_clock HTH Gerard From http Thu Mar 30 21:22:03 2006 From: http (Paul Rubin) Date: 30 Mar 2006 18:22:03 -0800 Subject: proposed proposal: set.values() References: <7x1wwjfr9k.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xbqvn8ib8.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > 1. It is pure duplication that *adds* keystrokes. Nobody says you shouldn't use list(s) if you know you're dealing with a set. The idea of s.values() is so you can duck-type between dicts and sets. > 2. It copies the wrong aspect of dict. A set is like dict.keys (no > duplicates, hashable), not dict.values (duplicates and non-hashables ok). I'd say keys is incorrect, since sets don't have keys: >>> import sets >>> s=sets.Set((1,2,3)) >>> s[1] Traceback (most recent call last): File "", line 1, in ? TypeError: unindexable object I don't think it's important that some values that can occur in dicts (e.g. non-hashables) can't occur in sets. There are similarly values for complex numbers that can't be expressed as floats, but that doesn't mean __add__ shouldn't work on both. > 3. It copies a workaround. Conceptually, dict.keys() and dict.items() > should each be a set, not list, and would have been if Python had had sets > at birth. Dict.values() should be a multiset or bag. The order of any is > purely artificial and random. Set.keys() or set.values() should be the set > itself. I guess it's ok if sets.items() is the same as sets.values(). Sets don't have keys. dict.values() is what it is for historical reasons as you state, and would be hard to change, so it makes sense for set.values() to work the same way. > 4. The workaround will change or even better go away. In 3.0, ,keys, > .values and .items not be lists. The initial proposal was to replace them > with iterators (the current iterkeys, etc). A current proposal (still in > development) is for an iterable set- or multiset-like view on the > underlying dict. I hadn't heard of this but it does make some sense. However, sets.values (and maybe sets.items) should be treated the same way, under my proposed proposal. From mensanator at aol.com Fri Mar 24 15:09:54 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 24 Mar 2006 12:09:54 -0800 Subject: converting to a binary number? In-Reply-To: References: Message-ID: <1143230994.574344.181800@z34g2000cwc.googlegroups.com> John Salerno wrote: > I'm having some trouble finding a function that converts numbers > (whether integer, hex, whatever) to its binary representation. Is there one? > > Thanks. Get the Gnu Multiple Precision library for Python module (Google GMPY). >>> import gmpy >>> help(gmpy.digits) Help on built-in function digits: digits(...) digits(x[,base]): returns Python string representing x in the given base (2 to 36, default 10 if omitted or 0); leading '-' present if x<0, but no leading '+' if x>=0. x must be an mpz, or else gets coerced into one. >>> for i in range(16): print gmpy.digits(i,2) 0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 From s323 at mail.ru Wed Mar 1 11:00:14 2006 From: s323 at mail.ru (Sergey) Date: Wed, 1 Mar 2006 19:00:14 +0300 Subject: why? [win32com/WMI] Message-ID: import win32com.client loc = win32com.client.Dispatch("WbemScripting.SWbemLocator") svc = loc.ConnectServer("srv", "root/cimv2", "Admin at zzz.ru", "******") sys = svc.get("Win32_Process") sys.create("notepad.exe") => Traceback (most recent call last): File "remote.py", line 6, in ? sys.create("notepad.exe") TypeError: 'int' object is not callable From singletoned at gmail.com Wed Mar 29 10:53:52 2006 From: singletoned at gmail.com (Ed Singleton) Date: Wed, 29 Mar 2006 16:53:52 +0100 Subject: Doc suggestions (was: Why "class exceptions" are not deprecated?) In-Reply-To: <34bb7f5b0603290752p48a1b818x4570d189153cbcdc@mail.gmail.com> References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com> <1143070060.384366.25480@z34g2000cwc.googlegroups.com> <1143574346.354680.136060@i39g2000cwa.googlegroups.com> <34bb7f5b0603290047o21b9a1b7k64cdd206f604fc10@mail.gmail.com> <34bb7f5b0603290752p48a1b818x4570d189153cbcdc@mail.gmail.com> Message-ID: <34bb7f5b0603290753w42d463d8gd975523a5ae7d7ab@mail.gmail.com> On 29/03/06, Ed Singleton wrote: > On 29/03/06, Fredrik Lundh wrote: > > > btw, one alternative could be to use an infogame site for this purpose: > > > > > > http://infogami.com > > > > > > this gives you revision history, a permissions system (limiting editing to > > > registered users might be a good idea), comments, an associated blog, > > > voting, feeds, change logs, etc. > > > > alright, I got bored and uploaded a copy of the current Python tutorial to > > > > http://pytut.infogami.com > > Damn. You beat me to it by an hour. > > http://singletoned.infogami.com/_special/index > > I had a nightmare with character encodings (mainly because I'm > terrible with them). I have a script written that does it all for me, > but it keeps choking on characters. I just tried randomly converting > things to Unicode at various points for over an hour until it worked. > > Ed > Also, your looks better than mine. Did you write a script to do the table of contents too? Ed From mhellwig at xs4all.nl Mon Mar 13 11:18:16 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Mon, 13 Mar 2006 17:18:16 +0100 Subject: PEP 8 example of 'Function and method arguments' Message-ID: <44159b49$0$11065$e4fe514c@news.xs4all.nl> While I was reading PEP 8 I came across this part: """ Function and method arguments Always use 'self' for the first argument to instance methods. Always use 'cls' for the first argument to class methods. """ Now I'm rather new to programming and unfamiliar to some basic concepts of OOP. However I wrote most of my classes in the new style way and by this I have always used 'self' for the first argument of an Instance method, but now I'm unsure what actually the difference is between an instance and a class method is and when to use it in which case. Could somebody please enlighten me (a rtfm/wrong newsgroup is just as welcome of course), preferably in a short code example? TIA -- mph From peter at engcorp.com Tue Mar 7 13:15:52 2006 From: peter at engcorp.com (Peter Hansen) Date: Tue, 07 Mar 2006 13:15:52 -0500 Subject: Pyserial again In-Reply-To: <98ar02h8ikt6ub9hh09r4cv4hgujpelcgl@4ax.com> References: <98ar02h8ikt6ub9hh09r4cv4hgujpelcgl@4ax.com> Message-ID: Richie Hindle wrote: > A piece of that code has been chopped off by someone's newsreader - it's the > body of a method, and ser.readline() is the last line of that method. I'm pretty sure that's true. Technically, however, it's still a guess, though at this point one I'm sure we're all comfortable making. That's why I asked about code *after* that last line. He replied there was no code before, but I think we can be generous in interpreting that (through the language barrier) as "no code after". Unfortunately, at this point we're getting into application design issues unless and until Luca can learn enough Python and other programming stuff to understand why "ser" is "going out of scope" because it's a "local variable" and is then being "garbage collected". (Luca, if you're reading, you really either have to just do exactly what Grant tells you :-), or learn about these issues enough to understand. If you don't know about object construction and destruction, memory allocation and garbage collection, the concept of "scope" and the difference between things like local variables, global variables, and attributes, we're going to continue to have an exceptionally difficult and frustrating time helping you. Serial ports aren't trivial, and combining them with a GUI program written by a rookie is a pretty big order. You can learn enough to figure this out, but it will be lots of work and a challenge. If you're up to it, please go read that "how to ask smart questions" page thoroughly if you haven't already, realizing that we're not trying to be rude by asking you to read it, and pay attention when someone asks you to try out different things, such as posting a small program that reproduces the problem, or post all the code rather than just snippets. Good luck.) -Peter From michael1cat at yahoo.com Thu Mar 30 03:35:53 2006 From: michael1cat at yahoo.com (Michael Paoli) Date: 30 Mar 2006 00:35:53 -0800 Subject: symbolic links, aliases, cls clear References: <1143672131.167324.36920@i39g2000cwa.googlegroups.com> Message-ID: <1143707753.031675.111630@v46g2000cwv.googlegroups.com> mp wrote: > i have a python program which attempts to call 'cls' but fails: > sh: line 1: cls: command not found > i'm using os x. [Note Followup-to: severely trimmed] I'd guestimate (those more familiar with python can probably fill in more relevant python specific details) that the python program is probably doing something like: system("cls") ... or whatever the python-specific way of writing something like that is. Most likely that was written, intended for some Microsoft DOS/Windows/XP or similar type of operating system - where CLS is a legitimate command (to clear the screen). On UNIX (and probably also OS X), there is no "cls" as a standard command, but there is the quite standard command "clear", to clear the "terminal" screen. In the land of UNIX, most languages implement the system() function or equivalent, by typically fork(2)ing and exec(3)ing (at least one of the exec(3) family of calls), generally invoking "the" or a default shell (typically /bin/sh) with a first option argument of "-c", and then the argument to system passed as one single string as the other argument to the shell. It would seem likely that python was "smart enough" (of course) to know on UNIX to implement system() as sh -c ..., rather than something like COMMAND /C ... or CMD /C ... as it would likely do on DOS/Windows/XP or similar. But "of course" python probably has no clue what the cls is that's handed to it with system(), and likely just blindly passes it on to the shell. The diagnostic you got would also seem to imply that's what happened (the shell (sh) couldn't find the cls command). ... as a matter of fact, if I try that on Debian GNU/Linux 3.1 (technically not "UNIX", but neither is OS X, but for practical purposes they're both quite sufficiently close), I get results that would appear exceedingly consistent with the hypothesis I put forth: $ sh -c cls sh: line 1: cls: command not found If it's desired to have the python program function as close to its (apparent) original intent as feasible, it may be desirable to: have it test the operating system, and if it is UNIX or similar, use clear, instead of cls ... or if one wants to port/adapt it to UNIX (and OS X, etc.), with no need or intention to move it back and forth or among significantly different operating systems, then perhaps consider simply replacing the system(cls) with system(clear), or whatever the precise suitable change in the python code would be. It would probably also be worth inspecting the code for other occurrences of system() that may also need to be adjusted or changed. Note also that some languages (e.g. Perl) will potentially take shortcuts with the system() function. For example, with Perl (paraphrasing and perhaps over-simplifying a bit) if Perl sees no need or reason to have to use the overhead of the shell to invoke the system() function, it will just quite directly (after the fork(2)) exec(3) the command, setting the argument(s) suitably. Python may (or may not) try similar shortcuts. For example, CLS, on DOS, etc., is internal to the "shell" (command interpreter), so, if python didn't find an external CLS command, it would have to pass it to the "shell", hoping the shell would know what to do with it. That would happen to work with DOS, but would generally fail on UNIX (where cls would generally not exist as a command, and wouldn't be built-in to the shell). From whumeniu+anti+spam at telus.net Thu Mar 16 13:55:02 2006 From: whumeniu+anti+spam at telus.net (Wade Humeniuk) Date: Thu, 16 Mar 2006 18:55:02 GMT Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> Message-ID: Without much testing. Common Lisp Pattern exclusions are made lispy. (defun all-lists (list length) (unless (zerop length) (if (= length 1) (mapcar #'list list) (loop for elt in list nconc (mapcar (lambda (rest) (cons elt rest)) (loop for rest on list nconc (all-lists rest (1- length)))))))) (defun cp-without-wc (source-list &rest patterns) (let* ((length (length (first patterns))) (all-lists (all-lists source-list length))) (dolist (pattern patterns) (setf all-lists (set-difference all-lists (mapcar (lambda (insertion) (let ((cp (copy-list pattern))) (loop for place on cp when (eql :any (car place)) do (setf (car place) (pop insertion))) cp)) (all-lists source-list (count :any pattern))) :test #'equal))) (remove-duplicates all-lists :test #'equal))) CL-USER 22 > (cp-without-wc '(a b) '(a :any b) '(b :any a)) ((A A A) (A B A) (B A B) (B B B)) CL-USER 23 > (cp-without-wc '(abc xyz) '(abc :any xyz)) ((XYZ XYZ XYZ) (XYZ XYZ ABC) (XYZ ABC XYZ) (XYZ ABC ABC) (ABC XYZ ABC) (ABC ABC ABC)) CL-USER 24 > (cp-without-wc '(a b) '(a :any :any)) ((B B B) (B B A) (B A B) (B A A)) CL-USER 25 > (cp-without-wc '(a b) '(a :any :any) '(b :any :any)) NIL CL-USER 26 > (cp-without-wc '(a b) '(:any :any b)) ((B B A) (B A A) (A B A) (A A A)) CL-USER 27 > Wade From jon+usenet at unequivocal.co.uk Tue Mar 28 04:36:38 2006 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 28 Mar 2006 09:36:38 GMT Subject: How do clients(web browser) close a python CGI program that is not responding? References: <1143521853.097142.57740@z34g2000cwc.googlegroups.com> Message-ID: In article <1143521853.097142.57740 at z34g2000cwc.googlegroups.com>, Sullivan WxPyQtKinter wrote: > Hi,there. Sometimes a python CGI script tries to output great > quantities of HTML responce or in other cases, it just falls into a > dead loop. How could my client close that CGI script running on the > server? I tried to use the STOP button in the web browser button, but > it does not work. It depends on what CGI framework you're using. If the user hits 'stop', the client browser should close its connection and your web server should close the pipe to your CGI process. I'd expect you to get a SIGPIPE when next trying to output data. > In addition, how could I configure that if a CGI program do not finish > its task in 20sec or so, it will be automatically terminated? Do you mean a specific CGI, or all CGIs in general? If it's in general then you need to see if your web server can be configured to do that. If it's a specific CGI, check out signal.alarm() or resource.setrlimit(resource.RLIMIT_CPU, ...). Apache has a RLimitCPU directive, but be careful with it since it may well not do what you expect. From jeremy at emperorlinux.com Wed Mar 8 10:17:08 2006 From: jeremy at emperorlinux.com (Jeremy L. Moles) Date: Wed, 08 Mar 2006 10:17:08 -0500 Subject: Having to "print" before method invocation? In-Reply-To: References: <1141828148.1863.9.camel@localhost.localdomain> Message-ID: <1141831028.1863.15.camel@localhost.localdomain> Hey Fredrik, thanks for responding. :) Your posts are always helpful and informative! On Wed, 2006-03-08 at 15:41 +0100, Fredrik Lundh wrote: > Jeremy L. Moles wrote: > > >I have an object (written as part C extension, part pure Python) called > > foo that I've been using without much fuss for a few months now. > > However, in my latest project (a rather large one involving > > multi-threading, pygtk, etc.), I'm seeing some really strange behavior > > with a particular instance of my foo object. > > > > About midway through my program, any attempt to use the instance fails; > > however, if I add print statements before trying to invoke methods on > > it, the foo object instance works fine. > > fails in what way? Unfortunately, very silently. There aren't any exceptions thrown or anything. The be more specific, the C part of the object is a wrapper around some socket Send/Recv functions (that interface w/ wpa_supplicant). The problem I'm getting is that unless I add that print statement, wpaobject.Recv() returns "", whereas with the print statement it returns what it should (a large string representing the response from wpa_supplicant). More strange is that this is the first time I've had to do this. Up until this point, every unittest and app has succeeded without such trickery. > if you get a spurious exception, it's very likely that your C extension sets the > exception state (either directly or because some API function it uses fails), but > forgets to report this back to Python. > > e.g. if you have a C function that does something like > > PyErr_SetString(PyExc_AttributeError, "blah blah"): > > Py_INCREF(Py_None); > return Py_None; > > instead of > > PyErr_SetString(PyExc_AttributeError, "blah blah"): > > return NULL; > > the interpreter won't raise the exception immediately (since it expected you to > return NULL if something went wrong), but the exception may still be raised at > a later time, if you run interpreter code that does something like > > do something > if (PyErr_Occurred()) > ... /* this will catch your error even if "something" succeeds */ ... > > *or* it may be masked, by code that does > > PyErr_Clear(); > do something > > the actual exception might give you additional clues (e.g. if you get a KeyError, > look for unchecked dictionary accesses in your code, etc). > > hope this helps! > > > > From aurora00 at gmail.com Tue Mar 21 13:09:36 2006 From: aurora00 at gmail.com (aurora) Date: Tue, 21 Mar 2006 10:09:36 -0800 Subject: Design mini-lanugage for data input References: <1142927112.502231.235450@t31g2000cwb.googlegroups.com> Message-ID: Yes. But they have different motivations. The mini-language concept is to design an input format that is convenient for human editor and that is close to the semi-structured data source. I think the benefit from ease of editing and flexibility would justify writing a little parsing code. JSON is mainly designed for data exchange between programs. You can hand edit JSON data (as well as XML or Python statement) but it is not the most convenient. Just consider you don't have to enter two quotes for every string object is almost liberating. These quotes are only artifacts for structured data format. The idea to design a format convenient for human and let code to parse and built the data structure. wy > Hmm, > Do you know about JSON and YAML? > http://en.wikipedia.org/wiki/JSON > http://en.wikipedia.org/wiki/YAML > > They have the advantage of being maintained by a group of people and > being available for a number of languages. (as well as NOT being XML > :-) > > - Cheers, Paddy. > -- > http://paddy3118.blogspot.com/ > From tim.peters at gmail.com Mon Mar 20 20:04:49 2006 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 20 Mar 2006 20:04:49 -0500 Subject: Python 2.5 Schedule In-Reply-To: <1142667600.257048.315910@z34g2000cwc.googlegroups.com> References: <1142667600.257048.315910@z34g2000cwc.googlegroups.com> Message-ID: <1f7befae0603201704pddadc21ie20e7460a7bb4724@mail.gmail.com> > For more details about the plan for Python 2.5, see: > > http://www.python.org/doc/peps/pep-0356/ Looks like links to PEPs are completely hosed at the moment. For example, the link above displays an empty directory, and http://www.python.org/doc/peps displays a directory full of empty directories. From gau.tai at gmail.com Fri Mar 10 16:07:08 2006 From: gau.tai at gmail.com (gau.tai at gmail.com) Date: 10 Mar 2006 13:07:08 -0800 Subject: MS Access db (mdb): viewing table attributes In-Reply-To: <1142023919.817724.200320@u72g2000cwu.googlegroups.com> References: <1142013201.717227.282050@i39g2000cwa.googlegroups.com> <1142015135.286529.209020@e56g2000cwe.googlegroups.com> <1142015868.754519.259200@e56g2000cwe.googlegroups.com> <1142023136.317554.144900@u72g2000cwu.googlegroups.com> <1142023694.024993.109730@j33g2000cwa.googlegroups.com> <1142023919.817724.200320@u72g2000cwu.googlegroups.com> Message-ID: <1142024827.953571.22950@v46g2000cwv.googlegroups.com> For more reference, I got my information to start this from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52267 When I try to run that code, it gives me this: File "C:\Python24\Lib\site-packages\win32com\client\util.py", line 83, in next return _get_good_object_(self._iter_.next()) pywintypes.com_error: (-2146825178, 'OLE error 0x800a0c26', None, None) The error is pointing to: "for idx in currTabl.Indexes:" From akameswaran at gmail.com Mon Mar 27 14:21:16 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 27 Mar 2006 11:21:16 -0800 Subject: problems with looping, i suppose In-Reply-To: <1143486277.480720.148040@t31g2000cwb.googlegroups.com> References: <1143486277.480720.148040@t31g2000cwb.googlegroups.com> Message-ID: <1143487276.684171.220440@e56g2000cwe.googlegroups.com> Ok I felt a little bad for my quick answer, these just seem like homework problems. first problem - it's scope. (there are two scope errors in the sample) white space is meaningful. get consistent with tabs or spaces, or choose an editor that replaces tab press with space. It'll make life a lot easier. And make copy and paste from the group easier for people trying to help :) Second problem (leap year) , you are catching the wrong kind of exception in that problem, so it's bubbling out as an unhandled exception. Use IDLE as a starting point, it's not much - but it would quickly expose these kinds of proboems. Run your code using idle or the interactive and you will see what is going on. As a side issue. On the second problem - you did say you just want to quit in the event of non numeric input, so it's WAD. But the underlying exception generated is not a NameError. Try catching any error and printing it. From tuvas21 at gmail.com Tue Mar 7 00:16:44 2006 From: tuvas21 at gmail.com (Tuvas) Date: 6 Mar 2006 21:16:44 -0800 Subject: Cryptographically random numbers In-Reply-To: References: <1141515788.580039.98240@v46g2000cwv.googlegroups.com> <1LXOf.44997$H71.35174@newssvr13.news.prodigy.com> <1141689228.273252.204350@e56g2000cwe.googlegroups.com> Message-ID: <1141708604.522128.52880@u72g2000cwu.googlegroups.com> Wow, that would have been nice to know... Oh well, I've already got the function, might as well use it... I'm starting to learn alot more of the standard libraries that exist for alot of the little functions. It seems like every project I have I build a misc.py file that contains several small, but useful functions, and quite often I discover there is a system library function to do just that. Oh well. Still, I've gone a long ways in my Python skills since I started 6 months ago:-) From bdesth.quelquechose at free.quelquepart.fr Sun Mar 19 11:24:55 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 19 Mar 2006 17:24:55 +0100 Subject: Counting number of each item in a list. In-Reply-To: <1142772092.958602.272260@e56g2000cwe.googlegroups.com> References: <1142772092.958602.272260@e56g2000cwe.googlegroups.com> Message-ID: <441d58f7$0$13046$626a54ce@news.free.fr> sophie_newbie a ?crit : > I have a list a little something like this: > > StringA > StringC > StringB > StringA > StringC > StringD > StringA > ... > etc. > > Basically I was wondering if there was an easy way to return how many > of each string are in the list, something like this: > > StringA - 3 > StringB - 1 > StringC - 2 > StringD - 1 There is. str_list = ['StringA', 'StringC', 'StringB', 'StringA', 'StringC', 'StringD', 'StringA' ] str_counts = dict((s, str_list.count(s) for s in set(str_list)) From fakeaddress at nowhere.org Tue Mar 7 00:04:52 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 07 Mar 2006 05:04:52 GMT Subject: Cryptographically random numbers In-Reply-To: <1141689228.273252.204350@e56g2000cwe.googlegroups.com> References: <1141515788.580039.98240@v46g2000cwv.googlegroups.com> <1LXOf.44997$H71.35174@newssvr13.news.prodigy.com> <1141689228.273252.204350@e56g2000cwe.googlegroups.com> Message-ID: Tuvas wrote: > Ahh, you are correct, that is a large bug... How about this one? Much better. Do note the comments from Emile van Sebille and Paul Rubin. There are some minor style and efficiency points, but it looks reasonable. Incidentally, as of Python 2.4, the standard library offers random.SystemRandom, which will generate integers in any desired range using os.urandom as the entropy source. -- --Bryan From jstroud at ucla.edu Fri Mar 3 17:52:28 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 03 Mar 2006 14:52:28 -0800 Subject: no-setup packages? In-Reply-To: <1141416367.750029.238980@i39g2000cwa.googlegroups.com> References: <1141416367.750029.238980@i39g2000cwa.googlegroups.com> Message-ID: xamdam wrote: > Hi all, > we have a situation where I need to deploy some python modules without > superuser permissions - is there a 'standard' way of doing it? > > Better yet, is there a way to deploy modules without running any > scripts at all? Tarball deployment of some sort? > > Particular things I have in mind are cx_Oracle, Cheetah. > > thanks, > max > Do you mean python eggs? From lezhewitt67 at hotmail.com Sat Mar 25 06:30:34 2006 From: lezhewitt67 at hotmail.com (lezhewitt67 at hotmail.com) Date: Sat, 25 Mar 2006 11:30:34 GMT Subject: ************************************LOOK AT THIS************************************* Message-ID: I am trying to gain sponsorship for a charity "The Stroke Association" for which i am doing the London Marathon in April this year. I would be greatful if all those persons who see this message would visit my webpage at www.justgiving.com/lezmarathon. All donations are welcome no matter how small. If anyone can think of any other groups that this message could be posted to, please contact me at my email address lezhewitt67 at hotmail.com. Please Give Generously many thanks LezHewitt From trepca at gmail.com Wed Mar 15 08:37:48 2006 From: trepca at gmail.com (Sebastjan Trepca) Date: Wed, 15 Mar 2006 14:37:48 +0100 Subject: Server applications - avoiding sleep In-Reply-To: <1142429205.440380.294650@z34g2000cwc.googlegroups.com> References: <1142429205.440380.294650@z34g2000cwc.googlegroups.com> Message-ID: You can create a Windows Service which will run as long as Windows are up, well, except if you stop it. You can find more info here: http://www.python.org/windows/win32/ Sebastjan On 15 Mar 2006 05:26:45 -0800, rodmc wrote: > I have written a small server application (for Windows) which handles > sending and receiving information from an instant messaging client and > a database. This server needs to run 24/7, however it stops when the > computer screen is locked. > > I assume there is a way to make it run in the background 24/7 but how > do I go about doing this? > > At present the application runs from within a wxPython GUI, however > this is only used to start and stop it. It could be entire faceless and > the GUI only used to execute it. > > Best, > > rod > > -- > http://mail.python.org/mailman/listinfo/python-list > From gene.tani at gmail.com Thu Mar 2 23:20:39 2006 From: gene.tani at gmail.com (gene tani) Date: 2 Mar 2006 20:20:39 -0800 Subject: do design patterns still apply with Python? In-Reply-To: References: <8SINf.1718$No6.40137@news.tufts.edu> Message-ID: <1141359639.306953.117990@v46g2000cwv.googlegroups.com> Terry Hancock wrote: > > This sounds like an article crying out to be written, > "(Learning) Design Patterns with Python". > > Has it been written already? > > Cheers, > Terry > > -- > Terry Hancock (hancock at AnansiSpaceworks.com) > Anansi Spaceworks http://www.AnansiSpaceworks.com There's a couple Alex M slideshows and a couple discussions of Creational/Structural / Behavioral patterns http://www.strakt.com/docs/ep04_pydp.pdf http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html http://www.pasteur.fr/formation/infobio/python/ch18s06.html http://www.sauria.com/~twl/conferences/pycon2005/20050323/Design%20Patterns%20and%20Python%20OOP%20-%20Objects%20By%20Design.html i think mostly i flip thru the Oreilly cookbook whenever i need something. From endavis at gmail.com Fri Mar 10 11:00:16 2006 From: endavis at gmail.com (Eric Davis) Date: Fri, 10 Mar 2006 11:00:16 -0500 Subject: suse linux 10 and wx.listctrl display issues In-Reply-To: <1141801934.075608.68840@j33g2000cwa.googlegroups.com> References: <1141799391.412666.160650@j52g2000cwj.googlegroups.com> <1141801934.075608.68840@j33g2000cwa.googlegroups.com> Message-ID: Put this in your main function before you instantiate your wx.App. if platform.system() == 'Linux': try: del os.environ['GTK_RC_FILES'] del os.environ['GTK2_RC_FILES'] except ValueError: pass This is a problem with SuSE, but I do it for all linuxes just in case. Eric ianar? wrote: > hum finally did find some SuSE specific RPM's through yast by setting > the media directory to mirros.kernel.org. Cool. But still the same > thing happens... > From ianare at gmail.com Fri Mar 3 12:04:19 2006 From: ianare at gmail.com (=?iso-8859-1?B?aWFuYXLp?=) Date: 3 Mar 2006 09:04:19 -0800 Subject: in need of some sorting help In-Reply-To: <1141275649.856712.313540@p10g2000cwp.googlegroups.com> References: <1141275649.856712.313540@p10g2000cwp.googlegroups.com> Message-ID: <1141405459.785318.156980@z34g2000cwc.googlegroups.com> sweet that works great! thanks again for all the help. From http Thu Mar 30 03:03:35 2006 From: http (Paul Rubin) Date: 30 Mar 2006 00:03:35 -0800 Subject: any() and all() on empty list? References: <442B9AF7.2010407@REMOVEMEcyber.com.au> Message-ID: <7xu09gicko.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Think of it this way: if all(seq) is true, shouldn't it be the case > that you can point to a specific element in seq that is true? No, all(seq) is true if you can't point to a specific element in seq that's false. From invalidemail at aerojockey.com Mon Mar 20 20:31:58 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 20 Mar 2006 17:31:58 -0800 Subject: Function params with **? what do these mean? In-Reply-To: References: <1142887602.977736.300990@u72g2000cwu.googlegroups.com> Message-ID: <1142904718.487434.97910@j33g2000cwa.googlegroups.com> Aahz wrote: > Personally, I think it's a Good Idea to stick with the semi-standard > names of *args and **kwargs to make searching easier... I usually do stick to these names (since the I usually only use them when forwarding arguments to another function, where such names are a pretty good description), but I can't think of any particular reason to search for all occurrences of them. Carl Banks From richie at entrian.com Tue Mar 7 10:39:16 2006 From: richie at entrian.com (Richie Hindle) Date: Tue, 07 Mar 2006 15:39:16 +0000 Subject: Pyserial again Message-ID: <98ar02h8ikt6ub9hh09r4cv4hgujpelcgl@4ax.com> [luca] > Here is my code; why after the readline the port close? > > ser = serial.Serial(0) > [...] > ser.readline() > > Why after this the port close. [Grant] > Because the "ser" object is never used after that point, so it > get's garbage collected and deleted. [Steve] > The "ser" name is still bound to the serial object, surely? A piece of that code has been chopped off by someone's newsreader - it's the body of a method, and ser.readline() is the last line of that method. -- Richie Hindle richie at entrian.com -- Richie Hindle richie at entrian.com From gregpinero at gmail.com Tue Mar 21 12:07:54 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Tue, 21 Mar 2006 12:07:54 -0500 Subject: Can XML-RPC performance be improved? In-Reply-To: <48apnrFj7ambU1@uni-berlin.de> References: <48apnrFj7ambU1@uni-berlin.de> Message-ID: <312cfe2b0603210907o40c377calcbb27d9e8f96da53@mail.gmail.com> Perhaps there's a hardware solution? Could you run more servers in parallel? Or have some sort of load distribution system? (Just some generic server tips, I don't know much about XML-RPC) -Greg On 3/21/06, Diez B. Roggisch wrote: > Sion Arrowsmith wrote: > > > I've got an established client-server application here where there > > is now a need to shovel huge amounts of data (structured as lists of > > lists) between the two, and the performance bottleneck has become > > the amount of time spent parsing XML (it's taking 100% CPU on one or > > other end of the connection and accounting for well over 50% of the > > total call time, to the extent that it's having a greater impact on > > performance than user interaction). And this is using SGMLOP for > > parsing -- I dread to think what it would be like with a slower > > parser. Anyone (Fredrik?) got any good ideas for tackling this > > problem? > > CORBA. Or TCP/IP directly. I know that isn't really the answer you're > looking for - but there is an overhead parsing XML, and that can't go away. > >From what I read at SGMLOP's site I doub't that you can get much faster - > because speed comes with sacrificing standard compliancy, which it already > seems to do. > > Regards, > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > -- Gregory Pi?ero Chief Innovation Officer Blended Technologies (www.blendedtechnologies.com) From asdrubale at gnx.it Fri Mar 3 04:46:09 2006 From: asdrubale at gnx.it (david mugnai) Date: Fri, 03 Mar 2006 10:46:09 +0100 Subject: how to overload sqrt in a module? References: <44079e05$1_3@newspeer2.tds.net> Message-ID: On Thu, 02 Mar 2006 19:24:48 -0800, mforbes wrote: [snip] > I know, but the point is that I want to allow the user of the module to be > able to specify which sqrt function should be used depending on the type > of x. Importing math in the module would prevent the user from using f() > with complex types (or dimensioned types for another example). If I don't misunderstood the problem, you can define an "init" method for your module_g (code not tested) module_g.py ----------- _functions = {} def init(mathmodule): _function['sqrt'] = getattr(mathmodule, 'sqrt', None) def _get(name): try: return _functions[name] except KeyError: raise TypeError("you have to initialize module_g") def sqrt(x): return _get('sqrt')(x) main.py ------- import math import module_g module_g.init(math) print module_g.sqrt(2) HTH From fredrik at pythonware.com Wed Mar 29 12:57:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 29 Mar 2006 19:57:00 +0200 Subject: Terminating a subprocess question References: <1143649900.667952.15410@t31g2000cwb.googlegroups.com><48vsl1Fmc3tkU1@uni-berlin.de> <1143654541.198515.62520@z34g2000cwc.googlegroups.com> Message-ID: Ernesto wrote: > Plus, everytime, I tried to use the read_all object, my program crashed > pretty hard... > > tn = telnetlib.Telnet("localhost",6000) > print tn.read_all() > # CRASH that's an unusual error message. are you sure you didn't get a traceback? if so, what did it say? From roy at panix.com Wed Mar 1 07:37:46 2006 From: roy at panix.com (Roy Smith) Date: Wed, 01 Mar 2006 07:37:46 -0500 Subject: PEP 354: Enumerations in Python References: <87accdplbj.fsf@rose.polar.local> <7xmzgdtjl0.fsf@ruckus.brouhaha.com> <873bi4z4w6.fsf@rose.polar.local> <7x7j7gjly8.fsf@ruckus.brouhaha.com> <46l8ibFbnfgeU3@individual.net> Message-ID: In article <46l8ibFbnfgeU3 at individual.net>, greg wrote: > Paul Rubin wrote: > > > Do you anticipate having parameters like socket.AF_INET that are > > currently integers, become enumeration members in future releases? > > Since these are derived from values defined > as integers in C, it's probably better to leave > them that way. There may be code that relies > on them being integers or having those integer > values. On a thin API like python's socket module, adding anything which isn't there in the lower level is a mistake (and making AF_INET an enum member would be adding something which isn't there). I just finished adding IPv6 support to a product that didn't have it before. We've got a "platform independent" socket interface which treats the address family as opaque data. It turns out, I had to make ZERO changes to this shim layer. Had the layer known more about address families, I would have had a lot more work to do. Consider, for example, Python running on a system with experimental AF_INET8 support at some point in the future. As it stands now, the Python library code doesn't need to know there's a new address family if all you want to do is open raw AF_INET8 sockets. From steve at REMOVETHIScyber.com.au Mon Mar 27 09:20:02 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 28 Mar 2006 00:20:02 +1000 Subject: determine file type References: Message-ID: On Sun, 26 Mar 2006 19:52:32 -0700, Mark Gibson wrote: > >> >> >> import os >> def test_file(filename, maxread=1024): >> if os.path.isdir(filename): >> return 'directory' >> afile = open(filename) # open as text >> for achar in afile.read(maxread): >> if ord(achar) > 127: >> return 'binary' >> return 'text' >> >> > > Pefect, thanks! Not only is it not perfect, as given it isn't even correct. >>> open("lots_of_nulls.bin", "w").write("\0" * 1024) >>> test_file("lots_of_nulls.bin") 'text' However, with a more careful algorithm for deciding what's text and what's not, the general approach is fine. -- Steven. From pydecker at gmail.com Fri Mar 3 07:19:34 2006 From: pydecker at gmail.com (Peter Decker) Date: Fri, 3 Mar 2006 07:19:34 -0500 Subject: Write a GUI for a python script? In-Reply-To: <1141377383.013956.44090@j33g2000cwa.googlegroups.com> References: <1141377383.013956.44090@j33g2000cwa.googlegroups.com> Message-ID: On 3 Mar 2006 01:16:23 -0800, peter.mosley at talk21.com > I, too, am a python newbie and have wrestled with GUI programming. I > think I am winning, but its been a struggle. I started with wxPython and struggled with it for a long time. I was able to get the job done, but using it never seemed natural. Then I found the Dabo project, whose ui module wraps wxPython into a much more Pythonic, consistent interface. Since then I've been able to create GUIs without much effort at all. I highly recommend Dabo if you are thinking about wxPython. -- # p.d. From bignose+hates-spam at benfinney.id.au Mon Mar 27 19:19:09 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 28 Mar 2006 10:19:09 +1000 Subject: instantiate a class with a variable References: <1143502361.763073.293340@u72g2000cwu.googlegroups.com> Message-ID: <87r74nmneq.fsf@rose.polar.local> "John" writes: > class foo: > def method(self): > pass > > x='foo' > > Can I use variable x value to create an instance of my class? You seem to be asking "is it possible to call an object whose name is stored in a string". The answer is yes:: >>> class Foo: ... pass ... >>> foo_name = 'foo' >>> foo_class = locals().get(foo_name) >>> bar = foo_class() >>> bar <__main__.Foo instance at 0x401e468c> Or, more succinctly but rather harder to follow:: >>> class Foo: ... pass ... >>> foo_name = 'foo' >>> bar = locals().get(foo_name)() >>> bar <__main__.Foo instance at 0x401e46ec> -- \ "I went to the cinema, it said 'Adults: $5.00, Children $2.50'. | `\ So I said 'Give me two boys and a girl.'" -- Steven Wright | _o__) | Ben Finney From ilias at lazaridis.com Tue Mar 21 13:05:48 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Tue, 21 Mar 2006 20:05:48 +0200 Subject: [CODE] - Python Newcomer Starting with Coding In-Reply-To: <441fde5d$0$29689$636a55ce@news.free.fr> References: <441fde5d$0$29689$636a55ce@news.free.fr> Message-ID: bruno at modulix wrote: > Ilias Lazaridis wrote: >> Where can I find practical coding examples for real life coding problems? > > Probably in real life code ?-) > >> Something like a categorized solution guide? > > Look for the Python cookbook (google is your friend). ... http://www.oreilly.com/catalog/pythoncook/ sorry, I've not clarified that I mean an free internet resource. >> * copy the content of the package folder to the created folder > > import shutil > help(shutil.copytree) ... this one was helpfull. thanks a lot. . -- http://lazaridis.com From jstroud at ucla.edu Fri Mar 17 16:28:29 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 17 Mar 2006 13:28:29 -0800 Subject: Importing an output from another function In-Reply-To: <1142629118.886810.251200@u72g2000cwu.googlegroups.com> References: <1142626528.204581.179350@v46g2000cwv.googlegroups.com> <1142627019.614450.250540@i40g2000cwc.googlegroups.com> <1142628076.041352.320560@i40g2000cwc.googlegroups.com> <1142629118.886810.251200@u72g2000cwu.googlegroups.com> Message-ID: Byte wrote: > Now what do I do if Func1() has multiple outputs and Func2() requires > them all to give its own output, as follows: > > import random > > def Func1(): > choice = ('A', 'B', 'C') > output = random.choice(choice) > output2 = random.choice(choice) > return output > return output2 The function will return at "return output", so "return output2" will never be reached. > def Func2(item1, item2): > print item1, item2 > > output1 = Func1() > Func2(output1) > > Thanks in advance, > -- /usr/bin/byte > Try this (I think its called "argument expansion", but I really don't know what its called, so I can't point you to docs): def Func1(): choice = ('A', 'B', 'C') output = random.choice(choice) output2 = random.choice(choice) return output, output2 def Func2(*items): print items output = Func1() Func2(*output1) BETTER: ======= You can also make a "generator" (which I have made generalized, which seems to be what you are striving for): def Gener1(num): choice = ('A', 'B', 'C') for i in xrange(num): yield random.choice(choice) def Func2(item): print item for item in Gener1(2): Func2(item) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From jstroud at ucla.edu Sat Mar 4 18:00:19 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 04 Mar 2006 15:00:19 -0800 Subject: How to except the unexpected? In-Reply-To: <7xk6b9kfib.fsf@ruckus.brouhaha.com> References: <7xk6b9kfib.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > James Stroud writes: > >>>approach. Basically this is reverse engineering the interface from the >>>source at the time of writing the app. >> >>This is using the source as documentation, there is no law against >>that. > > That's completely bogus. Undocumented interfaces in the library > source are allowed to change between Python versions and across Python > implementations. If you write your application according to the > documented interfaces in the Python manual, it should not break when > someone upgrades to the next Python release. You should not have to > depend on undocumented aspects of the Python implementation which > change out of sync with the application. > My suggestion was to use some common sense about the source code and apply it. I've wasted many hours programming to faulty documentation when a quick peek at the source code would have saved some serious time. How do you think I happened accross the technique? I would wager that, in 10 years time, the urllib2 module will not raise any exceptions that don't inheret from urllib2.URLError or a built-in (i.e. documented) exception; unless, of course, someone made a change in a deliberate attempt to win said wager ;o) >>How things are and how things should be have always been 2 entirely >>different things. See early books by Robert J. Ringer for a more >>complete discussion. > > That's like saying programs shouldn't have bugs, but they often do > anyway. It doesn't mean the bugs are a good thing or that they > shouldn't be fixed. The original reference was to the internet, which seems vast in its sources of unforseen peril. If some gracious soul aspires to fix every bug in the internet, I invite him to be my guest. James From petr at tpc.cz Wed Mar 1 08:07:41 2006 From: petr at tpc.cz (Petr Jakes) Date: 1 Mar 2006 05:07:41 -0800 Subject: Python Indentation Problems In-Reply-To: <1141021286.047172.278030@z34g2000cwc.googlegroups.com> References: <1141021286.047172.278030@z34g2000cwc.googlegroups.com> Message-ID: <1141218461.412331.114460@z34g2000cwc.googlegroups.com> Eric3 works great with spaces, tabs and even when imported code indentation is "mixed". I have got problems trying to import "mixed) code from other people. Settings > Preferences > Editor > General Tab width 8 Indentation width 4 (reasons why 8 and 4 are mentioned in previous postings in this thread) Than you can set the checkboxes: - Use tabs for indentation - Convert tabs upon open - Tab key indents - Auto indentation - Show Indentation Guides You can also see the different marks for tabs and for spaces in Eric3 (if set), so you will see, where is the problem in you code. My favorite options (I am trying to use spaces for indentation strictly) are: ===================================== - "Use tabs for indentation" - unchecked - "Convert tabs upon open" - checked ===================================== Because of that I am not getting to the troubles with indentation anymore. HTH Petr Jakes From bencvt at gmail.com Thu Mar 2 18:48:56 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 2 Mar 2006 15:48:56 -0800 Subject: in need of some sorting help In-Reply-To: <1141310917.304955.186080@i40g2000cwc.googlegroups.com> References: <1141275649.856712.313540@p10g2000cwp.googlegroups.com> <4406d5dd_1@newspeer2.tds.net> <1141310917.304955.186080@i40g2000cwc.googlegroups.com> Message-ID: <1141343336.934433.216120@t39g2000cwt.googlegroups.com> ianar? wrote: > However, i need the sorting done after the walk, due to the way the > application works... should have specified that, sorry. If your desired output is just a sorted list of files, there is no good reason that you shouldn't be able sort in place. Unless your app is doing something extremely funky, in which case this should do it: root = self.path.GetValue() # wx.TextCtrl input filter = self.fileType.GetValue().lower() # wx.TextCtrl input not_type = self.not_type.GetValue() # wx.CheckBox input matched_paths = {} for base, dirs, walk_files in os.walk(root): main.Update() # i only need the part of the filename after the # user selected path: base = base.replace(root, '') matched_paths[base] = [] for entry in walk_files: entry = os.path.join(base, entry) if not filter: match = True else: match = filter in entry.lower() if not_type: match = not match if match: matched_paths[base].append(entry) def tolower(x): return x.lower() files = [] # Combine into flat list, first sorting on base path, then full path for base in sorted(matched_paths, key=tolower): files.extend(sorted(matched_paths[base], key=tolower)) --Ben From tim at pollenation.net Tue Mar 14 17:36:15 2006 From: tim at pollenation.net (Tim Parkin) Date: Tue, 14 Mar 2006 22:36:15 +0000 Subject: Cheese Shop: some history for the new-comers In-Reply-To: References: <44126523$0$1016$afc38c87@news.optusnet.com.au> Message-ID: <4417455F.90406@pollenation.net> Fredrik Lundh wrote: >A.M. Kuchling wrote: > > > >>I've changed the PSF link, but am not sure what to do about the >>python-dev link. As others have noted, "Developers" is ambiguous >>about whether it's for people who develop in Python or who develop >>Python itself. "Core Development"? (Used on both perl.org and tcl.tk, so >>maybe this is the best option.) >> >> > >"core development" is fine with me. > > > > > I've tried this out on a test page and I think it works well.. I've also removed a couple of bits from the left hand nav and moved the style sheet switcher elsewhere (it probably should be in the help section). I think the left hand nav is a lot clearer if kept simple. Tim Parkin From andreas at nospam.openrts.org Tue Mar 7 18:27:17 2006 From: andreas at nospam.openrts.org (Andreas R.) Date: Wed, 08 Mar 2006 00:27:17 +0100 Subject: asynchat - operation could not complete w/ blocking Message-ID: Hi again, I'm using Python's asynchat module for networking. When calling the sendall() method of asynchat, I sometimes get the error message "the operation could not complete without blocking". So how do I enable blocking with synchat, or otherwise fix this error? Thanks for the help I've received with asynchat so far in this news group. - Andreas From rogerb at rogerbinns.com Sat Mar 11 23:18:50 2006 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 11 Mar 2006 20:18:50 -0800 Subject: Which GUI toolkit is THE best? References: <441172c2$1@news1.ethz.ch> Message-ID: "invitro81" wrote in message news:441172c2$1 at news1.ethz.ch... > But I've no idea which one I should use to start with.. One thing you'll need to carefully decide is where you want to end up. The different toolkits have different limits on where you can go. A simple example is printing. Some don't support it (eg Tkinter didn't 5 years ago when I last used it). If you will never need to print then that won't matter. Generally what you'll find is that the toolkits that let you do more are harder to get started with because you have to code in such a way as to let the more complicated features (eg printing) work, and the documentation is bigger because there is more to document. These are some of those areas to consider: Printing Can you print? Does the user get to use their operating system specific dialog boxes to choose printers etc? As a developer can you find out if the printer is colour or black and white? What about the paper size? HTML Does the toolkit have a way for you to display HTML? How complicated can the HTML be (eg CSS)? Can you embed widgets in the HTML? Threading Do you have to confine gui operations to one thread? How do you send a message from a worker thread to the gui thread (the gui thread will block in an event loop - that event loop needs to be able to be woken up from other threads) Native look and feel Will your users expect a native looking application? Will they want drag and drop? Do they expect rich objects on the keyboard? Is the toolkit available for all platforms you would want to run on (Windows, Linux, Mac, BSD etc) and their variations (different processors, 32 and 64 bit runtimes)? OLE Can you display other applications as a widget within yours? What about the other way round? Can you script other applications? (Python actually has the latter available on many platforms without the need for the gui toolkit to so) i18n/l10n Does the toolkit support Unicode? How easy is it to use with multiple languages? Additional packages What additional packages are there for the toolkit? For example Pmw provides more widgets to tkinter and their are GL packages for the various toolkits. If you are going to do graphics heavy stuff you'll want some way of hooking the toolkit with PIL. There should be some sort of demo available. wxPython has a fantastic one showing every single widget with code you edit to see what effect it has. The documentation should be good as well. Pick a random question such as "how do I delete all entries in a listbox begining with 'foo'" and see if you can work it out from the documentation. There should also be some sort of mailing list and user forums. Look for helpful answers being given with people being polite. What I would suggest you do is write a simple application in two or three different toolkits (eg convert temperature between F and C). You'll learn various ways of dealing with widget placement and sizers. (ie what happens if the user makes the containing window larger or smaller). My suggestions are to try PyGame, Tkinter and wxPython. You'll be better off having learned lessons from all 3 than just using one. The piece of good news is that to my knowledge applications written using any of the toolkits can be packaged up using tools like py2exe/py2app/cx_Freeze so that you can redistribute them to other users and those users will not have to know or care that you used Python and whatever toolkit. Roger From eyal.lotem at gmail.com Tue Mar 28 05:27:57 2006 From: eyal.lotem at gmail.com (Eyal Lotem) Date: Tue, 28 Mar 2006 12:27:57 +0200 Subject: To run a python script in all the machines from one server References: <1143539012.363882.74740@j33g2000cwa.googlegroups.com> Message-ID: muttu2244 at yahoo.com wrote: > Hi Everyone > > I want to run a python script in all the machines that are connected > through local network and collect the information about that machine > such as HDD size, RAM capacity(with number of slots) ,processer speed > etc. > > But i want to run a script from just the server, so that it should > start scripts in all other machines, and get their local machines > information and dump the same information in some FTP. > > Could you please let me know how can i do this?? > > Thanks > Yogi Take a look at: http://pybuild.sf.net/pyinvoke.html or http://rpyc.sourceforge.net From steve at REMOVETHIScyber.com.au Wed Mar 29 06:34:08 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 29 Mar 2006 21:34:08 +1000 Subject: any() and all() on empty list? References: <1143622860.716668.231370@v46g2000cwv.googlegroups.com> Message-ID: At risk of flogging a dead horse... On Wed, 29 Mar 2006 01:01:00 -0800, vdrab wrote: >> I'm completely on board with the semantics for any(). But all() bothers >> me. If all() receives an empty list, it will return True, and I don't >> like that. To me, all() should be a more restrictive function than any(), >> and it bothers me to see a case where any() returns False but all() >> returns True. > > Who should we call to report this fallacy? GvR? Goedel? Tarski? no, > wait... Frege ! or wait... actually, I think that must be Aristotle. > Sorry Aristotle, the ol' syllogisms have to go. > > ; -) > All silliness aside, the meaning of all() in python corresponds just > fine with "all" in both language and logic. > s. (Dis)proof by counter-example: GvR is in deep trouble -- the police now have sufficient evidence of his guilt to lock him away for life for all of the terrorist attacks he is suspected of: >>> def enough_evidence(crime): ... return True ... >>> suspected_attacks = [] >>> sufficient_proof = filter(enough_evidence, suspected_attacks) >>> guilty = all(sufficient_proof) >>> if guilty: ... print "Send him to Gitmo!" ... Send him to Gitmo! I understand and accept Tim Peter's explanation for why the proposed behaviour is the Right Way to handle all() and any() -- but that doesn't mean that there isn't a paradox buried in there. Notice that the police, by setting themselves the more difficult task of proving Guido's guilt on all() charges, can lock him up even though no crime was committed. Whereas, if they took the simpler task of merely proving his guilt on any() charge, Guido would be a free man: >>> guilty = any(sufficient_proof) >>> if not guilty: ... print "Walk free!" ... Walk free! While the implemented behaviour might be more practical than the alternatives, it is still worrying paradoxical. If "All sheep are woolly", then obviously it must also be true that "Any sheep is woolly". More formally, if all(X), then any(X) -- except for the case of empty X. Hmmm. -- Steven. From jbellis at gmail.com Mon Mar 20 13:21:59 2006 From: jbellis at gmail.com (Jonathan Ellis) Date: 20 Mar 2006 10:21:59 -0800 Subject: whats your favourite object relational mapper? In-Reply-To: References: <1142801641.638791.148370@e56g2000cwe.googlegroups.com> <1142819539.741782.189420@v46g2000cwv.googlegroups.com> <1142835121.089445.236070@v46g2000cwv.googlegroups.com> <1142873279.311421.325650@i39g2000cwa.googlegroups.com> Message-ID: <1142878919.891039.200410@e56g2000cwe.googlegroups.com> Steve Holden wrote: > I think describing this as Ian saying the code in its current form "is a > dead end" is to read rather more into the words than is actually there. Well, that may be. However, given that the 0.x code is so crufty that the v2 "refactor" is a multi-day (-week, now) process that merits a new project name, and there are enough architecture warts that it's not worth it to keep v2 backwards compatible, I'm not sure what requirements of being a dead end are missing here. :) I suppose that in one sense no OSS project is a dead end since you can always pick up the pieces yourself, but it's clear the 0.x series is not a place to expect much in the way of new developments from its author. -Jonathan From iainking at gmail.com Fri Mar 3 08:03:22 2006 From: iainking at gmail.com (Iain King) Date: 3 Mar 2006 05:03:22 -0800 Subject: object's list index In-Reply-To: <1141390100.640515.180680@u72g2000cwu.googlegroups.com> References: <1141388967.849854.239830@z34g2000cwc.googlegroups.com> <1141390100.640515.180680@u72g2000cwu.googlegroups.com> Message-ID: <1141391002.521371.179030@t39g2000cwt.googlegroups.com> Iain King wrote: > Iain King wrote: > > William Meyer wrote: > > > hi, > > > > > > I need to get the index of an object in a list. I know that no two objects > > > in the list are the same, but objects might evaluate as equal. for example > > > > > > list = [obj1, obj2, obj3, obj4, obj5] > > > for object in list: > > > objectIndex = list.index(object) > > > print objectIndex > > > > > > prints 0, 1, 2, 3, 2 instead of 0, 1, 2, 3, 4 because obj3 == obj5. I could loop > > > through the list a second time comparing id()'s > > > > > > for object in list: > > > objectIndex = 0 > > > for i in list: > > > if id(object) == id(i): > > > break > > > objectIndex += 1 > > > print objectIndex > > > > > > but that seems like a real ugly pain. Somewhere, someplace python is keeping > > > track of the current index in list, does anyone know how to access it? Or have > > > any other suggestions? > > > > Um, one of us is being really really dense today :) I hope it's not > > me... > > what's wrong with: > > > > i = 0 > > for object in list: > > objectIndex = i > > print objectIndex > > i += 1 > > > > Iain > > Reading it again, I'm thinking it probably is me... > > If you aren't looking them up sequentially then I think your second > example is the only way. You can make it a little prettier by using > 'object is i' rather than 'id(object) == id(i)'. > I think python only stores lists one way - i.e. each index maps to it's > value, but no backwards trace is kept from value to index. > > Iain OTOH, if memory is not an issue, you can create a lookup yourself: def createLookup(l): d = {} for index in xrange(len(l)): objID = id(l[index]) d[objID] = index return d lookup = createLookup(list) for i in list: objectIndex = lookup[id(i)] print objectIndex Iain From thomas at python.org Wed Mar 8 06:06:40 2006 From: thomas at python.org (Thomas Wouters) Date: Wed, 8 Mar 2006 12:06:40 +0100 Subject: mail.python.org disruption Message-ID: <9e804ac0603080306g6dfca8e7j94c9b4966ae9f171@mail.gmail.com> [ Mailed to python-dev and python-list, as that should cover most of the users ;P ] There was a slight disruption on mail.python.org this morning. For about three and a half hours, it was rejecting most of its mail with the message: Client host [....] blocked using singlehop.dsbl.org; Your mail has been rejected because the server you are sending to is misconfigured. The error means mail.python.org was using singlehop.dsbl.org as a DNSBL list, but that list doesn't exist, so it rejects all mail. Someone (not me :) added that blacklist at 08:15 local time (07:15 GMT) and I fixed it at 11:46 (10:46 GMT). Blame lingering PyCon-jetlag for me not catching it earlier, sorry. About 7759 mails were bounced, although a decent portion of them will have been actual spam (of which python.org gets massive amounts.) If you sent legitimate mail in that period, and got a bounce back with a message like the one above, it's safe to re-send it now. Sorry for the inconvenience. -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! -------------- next part -------------- An HTML attachment was scrubbed... URL: From irmen.NOSPAM at xs4all.nl Sun Mar 19 19:44:02 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 20 Mar 2006 01:44:02 +0100 Subject: Is there such an idiom? In-Reply-To: <1142813592.486643.111550@j33g2000cwa.googlegroups.com> References: <1142813592.486643.111550@j33g2000cwa.googlegroups.com> Message-ID: <441dfad2$0$11074$e4fe514c@news.xs4all.nl> Per wrote: > how to find the number of common items between two list in linear-time? > Not really sure about linear-time, but you could try the following: >>> a=[1,2,3,4] >>> b=[3,4,5,6] >>> set(a) & set(b) set([3, 4]) --Irmen From grante at visi.com Tue Mar 7 15:19:13 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 07 Mar 2006 20:19:13 -0000 Subject: Pyserial again References: <98ar02h8ikt6ub9hh09r4cv4hgujpelcgl@4ax.com> Message-ID: <120rqm12k3p31a@corp.supernews.com> On 2006-03-07, Peter Hansen wrote: > Serial ports aren't trivial, and combining them with a GUI > program written by a rookie is a pretty big order. You can > learn enough to figure this out, but it will be lots of work > and a challenge. If you're up to it, please go read that "how > to ask smart questions" page thoroughly if you haven't > already, There's even an Itialian translation: http://xoomer.virgilio.it/army1987k/ > realizing that we're not trying to be rude by asking you to > read it, and pay attention when someone asks you to try out > different things, such as posting a small program that > reproduces the problem, or post all the code rather than just > snippets. Good luck.) -- Grant Edwards grante Yow! ... Just enough at time to do my LIBERACE visi.com impression... From axel.bock.news at googlemail.com Mon Mar 27 03:19:09 2006 From: axel.bock.news at googlemail.com (Axel Bock) Date: 27 Mar 2006 00:19:09 -0800 Subject: COM object pointer cast Message-ID: <1143447549.045826.291850@i40g2000cwc.googlegroups.com> Hi, I am fooling around with the Python-COM bridge, and I have a little question with that. In the component I am using is a method which will return an "Entry" object - basically. In truth it returns some object which inherits from entry, and I know which one, but - as said - the method will only return the IEntry interface pointer. Now I would like to cast that one to the one I need :) . Is there an easy way to do it, or do I have to use the QueryInterface-method to get what I want? Greetings & thanks in advance, Axel. From deets at nospam.web.de Thu Mar 23 06:04:05 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 23 Mar 2006 12:04:05 +0100 Subject: Probelem about image size and dimensions References: <1143109000.672508.175070@t31g2000cwb.googlegroups.com> <48fbg4Fjqn9hU1@uni-berlin.de> <1143111286.875298.277290@z34g2000cwc.googlegroups.com> Message-ID: <48fdmpFk0bbbU1@uni-berlin.de> ChengGong wrote: > Thank you for your reply. I have been learning python only 2 weeks. > According what u said. I tried to import Image but there 's an error > on the server. > here is the message > Error Type: ImportError > Error Value: import of "Image" is unauthorized Are you by chance running under ZOPE? Then you'll need a so-called ExternalMethod for your code to import restricted modules. Diez From dinko.tenev at gmail.com Fri Mar 24 05:39:40 2006 From: dinko.tenev at gmail.com (Dinko Tenev) Date: 24 Mar 2006 02:39:40 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: <1143139987.254145.267980@g10g2000cwb.googlegroups.com> References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1143024937.827420.104100@i39g2000cwa.googlegroups.com> <20060322141400.1A00.1.NOFFLE@dthierbach.news.arcor.de> <1143110872.284192.325230@u72g2000cwu.googlegroups.com> <20060323134326.C29.0.NOFFLE@dthierbach.news.arcor.de> <1143134775.887696.5000@z34g2000cwc.googlegroups.com> <1143139987.254145.267980@g10g2000cwb.googlegroups.com> Message-ID: <1143196780.127188.289060@v46g2000cwv.googlegroups.com> wkehowski at cox.net wrote: > Call a wc 'free' if it satisfies the propery that every letter 'a' in > it appears only in the form '*a*', and 'anchored' otherwise. What if > all wc's are free? How does this affect the DFA? Does it minimize > nontrivially? Keep in mind I'm new to DFA theory. There would be no difference for single patterns, but I'm not sure into how large a DFA a set of those would combine. Cheers, Dinko From steve at REMOVETHIScyber.com.au Sat Mar 25 20:00:57 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 26 Mar 2006 11:00:57 +1000 Subject: years later DeprecationWarning References: <874q1qp51b.fsf@jidanni.org> <1143064740.510563.23150@v46g2000cwv.googlegroups.com> Message-ID: On Wed, 22 Mar 2006 13:59:00 -0800, Chris Lasher wrote: > Two things: > 1) math.floor returns a float, not an int. Doing an int() conversion on > a float already floors the value, anyways. No it doesn't, or rather, int() is only equivalent to floor() if you limit the input to non-negative numbers: int(-2.2) => -2, but floor(-2.2) should give -3. The standard definition of floor() and ceil() are: floor(x) = maximum integer n such that n <= x ceil(x) = minimum integer n such that n >= x or as Python functions: def floor(x): "Returns the maximum integer less than or equal to x" if x >= 0: return int(x) else: if x % 1: return int(x)-1 else: return int(x) def ceil(x): "Returns the minimum integer greater than or equal to x" return -floor(-x) or even simpler: from math import floor, ceil (Caution: the functions defined in the math module return the floor and ceiling as floats, not int, so you may want to wrap them in a call to int.) -- Steven. From g.brandl-nospam at gmx.net Tue Mar 14 08:16:51 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Tue, 14 Mar 2006 14:16:51 +0100 Subject: andmap and ormap In-Reply-To: References: <1142339035.687474.271120@p10g2000cwp.googlegroups.com> Message-ID: <47nu23Fgf6goU1@individual.net> Peter Otten wrote: > Python 2.5 will feature similar functions any() and all() which seem to have > a fixed predicate == bool, though. You cannot write all(predicate, list) but all(predicate(x) for x in list) Georg From steve at REMOVETHIScyber.com.au Thu Mar 9 06:39:04 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 09 Mar 2006 22:39:04 +1100 Subject: accesibility of the namespace References: <1141897375.385047.258520@j52g2000cwj.googlegroups.com> Message-ID: On Thu, 09 Mar 2006 01:42:55 -0800, Petr Jakes wrote: > In my code I have relatively wide dictionary definition (about 100 > rows). > > I would like to put it in to the different file (module) because of the > main code readability (say the name of the file will be > "my_dictionary.py") > > In the dictionary I have strings formatted using % operator like: > lcd={2:"Your credit= %3d" % (credit)} The values in the dictionary (e.g. "Your credit= 9.99", or whatever value credit actually has) are fixed at creation. I assume that means that credit etc. are also fixed values. > While I am trying to import my_dictionary in to the main code, I am > getting: > > exception unhandled NameError > name "credit" is not defined > > How can I organize my code so the "credit" variable will be "visible" > in the "my_dictionary" namespace? Put it in the same module as my_dictionary. E.g. # Module my_dictionary.py # which I hope will have a more sensible name before being used # for production-code credit = 27 foo = 15 lcd = {2: "Your credit= %3d" % credit} On the other hand, if credit is a calculated value, this might not be an easy thing to do. In that case, you can do this: # Module calculatevalues.py credit = some_function() foo = some_other_function() # Module my_dictionary.py import calculatevalues lcd = {2: "Your credit= %3d" % calculatevalues.credit} On the third hand, if the strings from the dictionary are supposed to be changed at run-time (which sounds more sensible to me) then do this: # Module my_dictionary.py lcd = {2: "Your credit= %3d"} # main program import my_dictionary ... lots of code here credit = 27 ... more code print lcd[2] % credit -- Steven. From siona at chiark.greenend.org.uk Tue Mar 28 10:03:23 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 28 Mar 2006 16:03:23 +0100 (BST) Subject: in-place string reversal References: <1143554931.104392.187480@i39g2000cwa.googlegroups.com> Message-ID: Sathyaish wrote: >How would you reverse a string "in place" in python? > [ ... ] >Forget it! I got the answer to my own question. Strings are immutable, >*even* in python. I'm not sure what that "*even*" is about, but glad that "You can't, strings are immutable" is a satisfactory answer. Rather than writing your own reversing code, you might like to look at: >>> "".join(reversed("foo")) -- \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 juho.schultz at helsinki.fi Fri Mar 10 05:20:11 2006 From: juho.schultz at helsinki.fi (Juho Schultz) Date: Fri, 10 Mar 2006 12:20:11 +0200 Subject: Python Evangelism In-Reply-To: References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> Message-ID: Magnus Lycka wrote: > rtilley wrote: > >> >> I think it's the name. Python. Let's change it to something nicer. >> Think about it... if you found a Ruby, you'd pick it up and put it in >> your pocket. If you ran across a Python, you'd run away. > > > I think you have a point, but I also think it's a bit > late to change it after 15 years or so, considering all > books, web sites etc. We're stuck with Python, and can > only do the best of that. Actually, in Swedish, "Jag > m?r pyton" i.e. "I feel like python" means "I feel > sick", and "det luktar pyton" i.e. "it smells python", > means "it stinks". That doesn't make Python easier to > sell here... Still to late to change... > In Finnish "ajaa k??rme pyssyyn" ("force a snake into a rifle") means doing something almost impossible. If you have to put a snake into a rifle, try Python - a bite does not kill you. So it works both ways. > I think a good example on the problem with letting > techies like us do naming is that grand successor > of Unix developed by the great minds at Bell Labs. > > First, they name it after a movie which is famous > for being exceptionally bad--Plan 9 (from outer space). > Really grand company there! > > Then, when they make a real product of it, they call > it Inferno, and some part of it gets called Limbo. > "Inferno - the Lamborghini Diablo of operating systems" What is the problem here? From david at fielden.com.au Thu Mar 16 15:50:16 2006 From: david at fielden.com.au (Rowdy) Date: Fri, 17 Mar 2006 07:50:16 +1100 Subject: Python Debugger / IDE ?? In-Reply-To: References: <1142357338.313046.139060@i39g2000cwa.googlegroups.com> <1142457652.412231.26050@v46g2000cwv.googlegroups.com> Message-ID: <4419CF88.4030304@fielden.com.au> Don Taylor wrote: > Is there a free or low-cost version of Delphi for Windows available > anywhere? > There used to be a Delphi 6 Personal Edition that was available free (for non-commercial use). You might still find it around somewhere. Rowdy From jarausch at skynet.be Sat Mar 25 10:58:09 2006 From: jarausch at skynet.be (Helmut Jarausch) Date: Sat, 25 Mar 2006 16:58:09 +0100 Subject: check object being a compiled regular expression Message-ID: <44256892$0$14646$ba620e4c@news.skynet.be> Hi, sorry, this seems to be a FAQ but I couldn't find anything I need to check if an object is a compiled regular expression Say import re RX= re.compile('^something') how to test "if RX is a compiled regular expression" type(RX) says but if isinstance(RX,_sre.SRE_Pattern) and if isinstance(RX,re._sre.SRE_Pattern) both fail. Many thanks for a hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From cito at online.de Thu Mar 23 18:09:55 2006 From: cito at online.de (Christoph Zwerschke) Date: Fri, 24 Mar 2006 00:09:55 +0100 Subject: Command line option -Q (floor division) Message-ID: I noticed that contrary to what is said in http://www.python.org/doc/2.2.3/whatsnew/node7.html, namely that integer divison should print deprecation warnings beginning with Python 2.3, even Python 2.4 is still quiet about it, i.e. you still need to explicitely set the -Q warn option to see the warnings. Is that by intent or has it simply been forgotten? -- Christoph From john_sips_tea at yahoo.com Fri Mar 17 10:38:43 2006 From: john_sips_tea at yahoo.com (john_sips_tea at yahoo.com) Date: 17 Mar 2006 07:38:43 -0800 Subject: Loop Backwards In-Reply-To: <7ejk12pn0ls3oms0al79ebg00lkfvhnbsq@4ax.com> References: <1139883877.323042.199040@o13g2000cwo.googlegroups.com> <43f19e0f$0$4761$636a55ce@news.free.fr> <1142459981.689594.261150@u72g2000cwu.googlegroups.com> <7ejk12pn0ls3oms0al79ebg00lkfvhnbsq@4ax.com> Message-ID: <1142609923.304613.253830@p10g2000cwp.googlegroups.com> Tim Roberts wrote: > "Dave" wrote: > > > >Please be mindful of making statements such as: > >"it's silly to believe both will behave equally" > > > >One of the greatest weaknesses of Python is the less than friendly > >attitude Pythonistas display towards one another. > > I don't know how much Usenet experience you've had, but comp.lang.python is > one of the friendliest places in the comp.lang universe. Newbie questions > get answered without derision, and disagreements are handled with spirited > discussion, instead of flames and insults. Compare, for example, to > comp.lang.c and comp.lang.c++. It's possible that english may not be Felipe's native language, and Dave may not've thought of that. To a native english speaker, Felipe's comment (which was very helpful!) could've also been construed as being slightly rude. Perhaps Felipe meant to write "mistaken" instead of "silly". Also, as an aside, smileys are always helpful on usenet. :) > [snip] I've looked at Ruby, but syntactically it > will never sway me from Python. Same here. From barmenkov at bpc-dot-ru.no-spam.invalid Wed Mar 15 08:10:33 2006 From: barmenkov at bpc-dot-ru.no-spam.invalid (PyDenis) Date: 15 Mar 2006 13:10:33 GMT Subject: WORKAROUND References: <4417d37c$0$76222$892e7fe2@authen.yellow.readfreenews.net> Message-ID: <44181249$0$76048$892e7fe2@authen.yellow.readfreenews.net> > Fredrik Lundhwrote: Could you perhaps use basic netiquette stuff, such as sticking to the same sub- > ject line for followup posts in the same thread, and including a least some trace > of the post you're commenting on ? > > (this would be less of a problem if everyone was reading your posts in a news- > reader, but this group is available in many different forms...) > > Excuse me, please. I mean, that 1. When I post new message to WEBFORUM (not a Mailing List nor News Group) not to include even part of message. 2. About subject line: if this forum huge depends from subject line, this field must be disabled or set to "RE: % "+ (orig_msg.subject) by forum admins. Forum using some webforum engine, and easiest way to format messages - tune it up accurately instead of messaging about netiquette. 3. I receive message about topic posts without host name, so could go in Browser History to find it. I mean, misplaced 'netiquette' eclipsed by this bug: Hello, You are receiving this email because you are watching the topic, "Re: WORKAROUND" at niXforums. This topic has received a reply since your last visit. You can use the following link to view the replies made, no more notifications will be sent until you visit the topic. http:///files/forum/viewtopic.php?p=730860#730860 If you no longer wish to watch this topic you can either click the "Stop watching this topic link" found at the bottom of the topic above, or by clicking the following link: http:///files/forum/viewtopic.php?t=136721&unwatch=topic -- Thanks, The Management Please, sorry for my english. From lycka at carmen.se Wed Mar 8 08:09:26 2006 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 08 Mar 2006 14:09:26 +0100 Subject: ODBC module and strange date reference <...> In-Reply-To: <1141766947.945596.180030@j52g2000cwj.googlegroups.com> References: <1141294036.353794.211450@i39g2000cwa.googlegroups.com> <1141766947.945596.180030@j52g2000cwj.googlegroups.com> Message-ID: dananrg at yahoo.com wrote: > I'm all for using for the latest version of Python. I'm just now > learning about Python classes, and it seems like there were some > significant changes at 2.2. I don't remember exactly what appeared when, but nothing you learn with 2.1 will stop working in 2.2 (I think--at least nothing broke for me, and I haven't heard of any problems in this regard). On Windows, you might have problems crossing the 2.2 -> 2.3 gap if you use non-ASCII characters in the source code. That's the only upgrade problem I ever had from 1.4.2 to 2.4.2... From s99999999s2003 at yahoo.com Thu Mar 16 05:32:37 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 16 Mar 2006 02:32:37 -0800 Subject: comparing huge files In-Reply-To: References: <1142475204.998414.213520@j52g2000cwj.googlegroups.com> Message-ID: <1142505157.496128.148740@e56g2000cwe.googlegroups.com> thanks for the reply, I have used another method to solve my problem. ie 1) get the total count of the first file 2) write this total count to basecnt eg basecnt 3) get another file, get the total count of this file. eg filecnt 4) if filecnt > basecnt, read in the values from file[basecnt:filecnt] 5) if filecnt < basecnt, overwrite original basecnt and start over again. basically, the problem domain is i want to get the most current records from a log file to review after every 3 hours. so this log file will increase or accumulate. From steve at holdenweb.com Tue Mar 7 10:20:58 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 07 Mar 2006 15:20:58 +0000 Subject: Pyserial again In-Reply-To: <120r82c3co02d94@corp.supernews.com> References: <1141661808.753184.157150@e56g2000cwe.googlegroups.com> <1141665448.418740.167910@i40g2000cwc.googlegroups.com> <120ossf55scsj8b@corp.supernews.com> <1141675566.162480.148260@v46g2000cwv.googlegroups.com> <1141681967.017912.180250@j33g2000cwa.googlegroups.com> <1141721704.444044.212620@p10g2000cwp.googlegroups.com> <120r82c3co02d94@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2006-03-07, luca72 wrote: > > >>Here is my code; why after the readline the port close? >> >> ser = serial.Serial(0) >> ser.baudrate = 9600 >> ser.parity = serial.PARITY_ODD >> ser.stopbits = serial.STOPBITS_TWO >> ser.bytesize =serial.EIGHTBITS >> ser.setRTS(level = 0) >> ser.setDTR(level = 0) >> ser.timeout = 1 >> >> ser.readline() >> >> Why after this the port close. > > > Because the "ser" object is never used after that point, so it > get's garbage collected and deleted. > ???? The "ser" name is still bound to the serial object, surely? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From ptmcg at austin.rr._bogus_.com Thu Mar 30 11:05:39 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 30 Mar 2006 16:05:39 GMT Subject: any() and all() on empty list? References: <442B9AF7.2010407@REMOVEMEcyber.com.au> <7xu09gicko.fsf@ruckus.brouhaha.com> <442BAAA5.8010009@REMOVEMEcyber.com.au> Message-ID: "Antoon Pardon" wrote in message news:slrne2nogp.e68.apardon at rcpc42.vub.ac.be... > Op 2006-03-30, Steven D'Aprano schreef : > > > So, these flying elephants -- are they pink or not? > > They are both. > That would make them Schr?dinger elephants! -- Paul From alainpoint at yahoo.fr Mon Mar 13 03:34:31 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 13 Mar 2006 00:34:31 -0800 Subject: Is this possible in Python? Message-ID: <1142238871.199749.243470@p10g2000cwp.googlegroups.com> Hi I wonder if Python is capable of the following: define a function which returns its argument. I mean: def magic_function(arg): ...... some magic code ... that behaves the following way: assert magic_function(3+4)=="3+4" assert magic_function([i for i in range(10)])=="i for i in range(10)]" It is not trivial at all and might require some bytecode hacking that i am unable to do myself BUT you are the experts ;-) Alain From harlinseritt at yahoo.com Fri Mar 24 10:12:35 2006 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 24 Mar 2006 07:12:35 -0800 Subject: Caching in memory for Apache In-Reply-To: <1143212200.835484.324420@i39g2000cwa.googlegroups.com> References: <1143212200.835484.324420@i39g2000cwa.googlegroups.com> Message-ID: <1143213154.946349.196380@i40g2000cwc.googlegroups.com> Pickle (http://www.network-theory.co.uk/docs/pytut/tut_58.html) comes to mind when anyone mentions wanting to save a value, method, object, etc without writing to storage (file or db). Is it possible for you to post some code? There may be an alternative algorithm so you can avoid writing to "memory." Harlin Seritt From __peter__ at web.de Fri Mar 10 03:28:35 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 10 Mar 2006 09:28:35 +0100 Subject: How to pop random item from a list? References: <1141970390.167455.152820@j52g2000cwj.googlegroups.com> <1141971152.31649.6.camel@blackwidow> Message-ID: marduk wrote: > item = mylist.pop(random.randint(0,len(mylist))) This is broken because randint(a, b) may return b. I prefer randrange(len(mylist)) over randint(0, len(mylist)-1) as a fix. Peter From xavier.morel at masklinn.net Mon Mar 6 11:22:20 2006 From: xavier.morel at masklinn.net (Xavier Morel) Date: Mon, 06 Mar 2006 17:22:20 +0100 Subject: Why I chose Python over Ruby In-Reply-To: <874q2bpv5q.fsf@wilson.homeunix.com> References: <1141573450.667103.8930@z34g2000cwc.googlegroups.com> <874q2bpv5q.fsf@wilson.homeunix.com> Message-ID: Torsten Bronger wrote: > Yes, however, this is also true for Python in my opinion. > Ruby's ability to generate DSLs is an order of magnitude better than Python's at least. I only know of the Lisp dialects that get better at DSLs. Check Rails' validation methods (in the models), or if you don't want to dwelve into rails (which I do understand), go check Why's "Dwemthy's Array" (http://poignantguide.net/dwemthy/) (note: you may need to read Why's Poignant Guide to Ruby first, the creation of the Array itself is fairly tough stuff with metaprogramming black magic and all). From steve at REMOVETHIScyber.com.au Sat Mar 4 03:29:58 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 04 Mar 2006 19:29:58 +1100 Subject: add an asynchronous exception class References: <7x3bhysotm.fsf_-_@ruckus.brouhaha.com> Message-ID: On Sat, 04 Mar 2006 08:41:48 +0100, Fredrik Lundh wrote: > Paul Rubin wrote: > >> I'd like to suggest adding a builtin abstract class to Python called >> AsynchronousException, which would be a subclass of Exception. The >> only asynchronous exception I can think of right now is >> KeyboardInterrupt, so KeyboardInterrupt would become a subclass of >> AsynchronousException instead of being a direct subclass of Exception. > > PEP 348 addresses this by moving special exceptions out of the > Exception hierarchy: > > http://www.python.org/peps/pep-0348.html The PEP has been summarily rejected, perhaps because it was too broad in the changes it suggested. -- Steven. From andreas at openrts.org Wed Mar 1 13:43:04 2006 From: andreas at openrts.org (Andreas R.) Date: Wed, 01 Mar 2006 19:43:04 +0100 Subject: asynchat network send problems Message-ID: Hello, I'm using Python's asynchat module for network support in a Python-based game, and I run into two problems, both of which occur at random times. Most of the time, the network sending and receiving is perfect, but about 1 out of 10 times, it fails with one of these errors: -- Problem 1. When sending data, I sometimes the following exception: Handler connected 127.0.0.1:1242 at 0x2977800> (socket.error:(9, 'Bad file descriptor') [C:\Python24\lib\asynchat.py|initiate_send|219] [C:\Python24\lib\asyncore.py|send|332] [C:\Python24\lib\socket.py|_dummy|144]) -- Problem 2. Receiving data on the client is not always the same size as the data which is sent from the server. Network server is found here http://svn.gna.org/viewcvs/openrts/trunk/openrts/client/networkclient.py?rev=39&view=markup Network client is found here: http://svn.gna.org/viewcvs/openrts/trunk/openrts/server/clienthandler.py?rev=41&view=markup This is the sequence for sending data: 1. In clienthandler.py the method send_to_client() is called with whatever data should be sent to the client. 2. send_to_client() compresses the data, and passes it to the push() method of asynchat. 3. Client receives the data, and called found_terminator() in networkclient.py 4. In the found_terminator() method, the data is attempted to be uncompressed, but it failes, since the received data does not have the same size as the data which is sent. Sometimes, the difference in size is often 512 between client and server, when running len(packet) on the *compressed* packed. The len() of a large packet is usually about 64969. Complete source code is available at http://svn.gna.org/daily/openrts-snapshot.tar.gz Thanks anyone for the help, - Andreas R. www.openrts.org From gongcheng_g at hotmail.com Fri Mar 24 08:08:07 2006 From: gongcheng_g at hotmail.com (ChengGong) Date: 24 Mar 2006 05:08:07 -0800 Subject: Upload and Resize image problem HELP!!! Message-ID: <1143205687.560795.225840@e56g2000cwe.googlegroups.com> I use following Python Script to upload file and image's but I can not specify a folder to store image. can any one help me? And I want to resize all the pictures, What shall I do? Finished thanks Cheng From duncan.booth at invalid.invalid Fri Mar 17 13:13:24 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2006 18:13:24 GMT Subject: Problem with C-API References: <441af112$0$8332$da0feed9@news.zen.co.uk> Message-ID: John Dean wrote: > PyRun_String("def title();", Py_file_input, dict, dict); > PyRun_String("\treturn 'Foo Bar'", Py_file_input, dict, dict); > PyRun_String("x = title()", Py_file_input, dict, dict); > PyObject * result = PyRun_String("print x", Py_file_input, dict, dict); > printf( "The result is %s\n", PyObject_AsString( result ); > > Each line throws an error. Please don't paraphrase your code when asking questions such as this. The code above doesn't even compile (unmatched parentheses) so any response must be a guess as to which parts were wrong in your original code and which errors you introduced just for the posting. Each call to PyRun_String is independant. You seem to think you can call the function with part of your source code and then continue with more of the source in another call. You cannot. Try concatenating the lines together to at least make complete statements. Also make sure to handle the result from every call to PyRun_String: check it for null, if it is null you should format and print the error message. The following is your code rewritten as a working program. When you run it, it will tell you about the syntax error in your Python code. Fix that and you will see your program output. #include void run() { PyObject *dict = PyDict_New(); PyObject *result; if (dict==NULL) { PyErr_Print(); return; } result = PyRun_String("def title();\n\treturn 'Foo Bar'\n", Py_file_input, dict, dict); if (result==NULL) { PyErr_Print(); return; } else { Py_DECREF(result); } result = PyRun_String("x = title()", Py_file_input, dict, dict); if (result==NULL) { PyErr_Print(); return; } else { Py_DECREF(result); } result = PyRun_String("print x", Py_file_input, dict, dict); if (result==NULL) { PyErr_Print(); return; } else { PyObject *rString = PyObject_Str(result); if (rString==NULL) { Py_DECREF(result); PyErr_Print(); return; } printf( "The result is %s\n", PyString_AsString(rString)); Py_DECREF(rString); Py_DECREF(result); } } int main(int argc, char **argv) { Py_Initialize(); run(); } From sjmachin at lexicon.net Thu Mar 23 17:33:19 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 24 Mar 2006 09:33:19 +1100 Subject: encoding problems =?ISO-8859-1?Q?=28=E9_and_=E8=29?= In-Reply-To: References: <44230fa6$1@news.eftel.com> Message-ID: <4423223d$1@news.eftel.com> On 24/03/2006 8:36 AM, Peter Otten wrote: > John Machin wrote: > >>You can replace ALL of this upshifting and accent removal in one blow by >>using the string translate() method with a suitable table. > > Only if you convert to unicode first or if your data maintains 1 byte == 1 > character, in particular it is not UTF-8. > I'm sorry, I forgot that there were people who are unaware that variable-length gizmos like UTF-8 and various legacy CJK encodings are for storage & transmission, and are better changed to a one-character-per-storage-unit representation before *ANY* data processing is attempted. :-) Unicode? I'm just a benighted Anglo from the a**-end of the globe; who am I to be preaching Unicode to a European? (-: From ethrandil at gmx.net Fri Mar 24 06:27:26 2006 From: ethrandil at gmx.net (Clemens Hepper) Date: Fri, 24 Mar 2006 12:27:26 +0100 Subject: Bitwise OR? In-Reply-To: <1143190128.783253.62430@i40g2000cwc.googlegroups.com> References: <1143187977.384459.225840@i40g2000cwc.googlegroups.com> <1143190128.783253.62430@i40g2000cwc.googlegroups.com> Message-ID: To look at the bit-structure i've implemented a little function: def bitstring(number, digits=32): """lsb------>msb""" result = "" for a in xrange(digits): if number & 1: result += '1' else: result += '0' number >>= 1 return result I wonder if there is something like sizeof() for int numbers. mfg - eth From inyeol.lee at siliconimage.com Mon Mar 27 16:51:22 2006 From: inyeol.lee at siliconimage.com (Inyeol Lee) Date: Mon, 27 Mar 2006 13:51:22 -0800 Subject: OT: unix newbie questions In-Reply-To: <1143287156.026223.320310@i40g2000cwc.googlegroups.com> References: <1143287156.026223.320310@i40g2000cwc.googlegroups.com> Message-ID: <20060327215122.GB17716@siliconimage.com> On Sat, Mar 25, 2006 at 03:45:56AM -0800, Gerard Flanagan wrote: [...] > * If I want to do : > > mv mypackage-1.0.2.tar.gz subdir/mypackage-1.0.2.tar.gz > > then tab-completion gives me the first occurrence of the file, but I > have to type the second occurrence - is there a way of not having to > type it? In this specific case you don't need second filename. mv mypackage-1.0.2.tar.gz subdir/ is enough. If you need filename for some reason, use this. mv mypackage-1.0.2.tar.gz subdir/mypackage-1.0.2.tar.gz.backup => mv mypackage-1.0.2.tar.gz subdir/!#:1.backup This works for both bash and (t)csh. --Inyeol From xkenneth at gmail.com Fri Mar 24 03:12:57 2006 From: xkenneth at gmail.com (xkenneth) Date: 24 Mar 2006 00:12:57 -0800 Subject: Bitwise OR? Message-ID: <1143187977.384459.225840@i40g2000cwc.googlegroups.com> Why is 3500 | -67 equal to 3500 instead of -3567? From bearophileHUGS at lycos.com Mon Mar 6 20:34:40 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Mar 2006 17:34:40 -0800 Subject: Python advocacy in scientific computation In-Reply-To: <1141618661.103690.153630@u72g2000cwu.googlegroups.com> References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> <1141583453.403143.189400@i40g2000cwc.googlegroups.com> <1141589892.094037.18410@i40g2000cwc.googlegroups.com> <1141618661.103690.153630@u72g2000cwu.googlegroups.com> Message-ID: <1141695280.402893.27290@p10g2000cwp.googlegroups.com> Michael Tobis: > Python plays so well with others. For many applications, NumPy is fine. > Otherwise write your own C or C++ or F77; building the Python bindings > is trivial. On Windows I have found that creating such bindings is very very difficult... I have succed only partially, with C++, and I've had to compile Python with MinGW (a compilation succed at about 95%). It's not easy and surely not trivial (for me). Bye, bearophile From tjreedy at udel.edu Wed Mar 29 21:19:52 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 29 Mar 2006 21:19:52 -0500 Subject: is 2.4.3 final? References: <8fDWf.1858$No6.41986@news.tufts.edu> Message-ID: "John Salerno" wrote in message news:8fDWf.1858$No6.41986 at news.tufts.edu... >I just noticed on one page of the Python website that it said: > > "We are pleased to announce the release of Python 2.4.3 (final), a > bugfix release of Python 2.4, on March 29, 2006." I believe today was the target date for this. Given that there have been no mentions of problems either here or on py-dev, I would expect it to have appeared. > Yet elsewhere it refers to it as a "release candidate" and still refers > to 2.4.2 as the "current production version". You seem to have caught the site in an inconsistent state. Perhaps you could revisit in a day and if problems continue, email the web maintainers (link on sidebar) with the cut and pasted urls of offending pages. Terry Jan Reedy From onurb at xiludom.gro Tue Mar 7 04:30:42 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 07 Mar 2006 10:30:42 +0100 Subject: Checking function calls In-Reply-To: References: Message-ID: <440d52ef$0$12876$626a54ce@news.free.fr> James Stroud wrote: (snip) > Since python is "weakly typed", s/weakly/dynamically/ (snip) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jimlewis at emachineshop.com Mon Mar 13 05:18:54 2006 From: jimlewis at emachineshop.com (jimlewis at emachineshop.com) Date: 13 Mar 2006 02:18:54 -0800 Subject: python crashes in Komodo In-Reply-To: References: <1142156538.647430.318350@z34g2000cwc.googlegroups.com> Message-ID: <1142245134.456384.303570@i39g2000cwa.googlegroups.com> > any non-standard (i.e. non-bundled) C extensions ? No. From chris at acel.co.uk Mon Mar 13 04:54:09 2006 From: chris at acel.co.uk (Chris Bingham) Date: 13 Mar 2006 01:54:09 -0800 Subject: Newbie - Running Commands Interactively Message-ID: <1142243649.463635.235440@z34g2000cwc.googlegroups.com> Hi everyone, I'm new to python, and I was wondering if anyone could help me with a couple of problems I've hit please? I'm trying to write a wrapper script for the passwd command, so that we can log everytime someone uses it, which options they used with it and if they succeeded or cancelled the command. The idea is that it'll look to the user like they're running the original system passwd command, but actually they're running it though this script. At the moment my script looks like this: #!/usr/bin/env python import os import coLog import sys result='failed' if len(sys.argv) > 1: cmd="passwd" for arg in sys.argv[1:]: cmd=cmd + " " + arg else: cmd="passwd" cmdRun=os.popen(cmd) result=str(cmdRun.readlines()) print result subResult=result.find('successfully') print subResult if subResult != '-1': coLog.add('Passwd', 'The user successfully executed the following command: ' + cmd, 'CLI') else: coLog.add('Passwd', 'The user executed the following command, but it failed or was cancelled: ' + cmd, 'CLI') # EOF The 'coLog' module that get's imported at the start is 1 I wrote to do the actual logging, so that i can easily reuse the code in other scripts. I've got 2 problems with it that i just haven't been able to fix; 1. Firstly, if I use os.popen to execute the command, the first & last lines of the command's output don't get displayed, i can get them later from the 'cmdRun' variable and print them, but then it doens't look like the original passwd command. I've found that using os.system instead fixes this issue, but then pressing ctrl-c during the command causes the shell ure in to go cooco-lala on u! :) os.popen works correctly with ctrl-c. I also tried os.popen2, but this caused the passwd command to go nuts! 2. Secondly, if ctrl-c is pressed the script gets killed along with the command, so it doens't log cancelled commands. I've tried using various variations of 'try, except', including catching the KeyboardInterrupt and catching all exceptions, but nothing seemed to work! I've been struggling with these 2 issues for the last week, and so far no joy. If anyone has any idea how to fix them I'd really appreciate the help! :) Thanks in advance for any help anybody can give, Chris From wescpy at gmail.com Tue Mar 7 13:20:58 2006 From: wescpy at gmail.com (w chun) Date: Tue, 7 Mar 2006 10:20:58 -0800 Subject: ANN: 2006 Python training courses, San Francisco Message-ID: <78b3a9580603071020k59e65356rc8f9279181a826d2@mail.gmail.com> WE are giving 4 more Python training sessions (held near the San Francisco airport) for the remainder of this year. For the first time, there will be an "advanced" Python course available to the public. In fact, we've added the March intro course date for those prepping to take the advanced class in May. You may register for any of the 4 courses/dates below. (Intensive) Introduction to Python March 29-31, 2006 August 16-18, 2006 Advanced Python Programming May 17-19, 2006 November 8-10, 2006 LOCALS: it'll be at a hotel with BART and CalTrain access (San Bruno stations) VISITORS: free shuttle directly from the San Francisco airport, lots of free food and wireless DISCOUNTS available. for more info and details, go to http://cyberwebconsulting.com and click "Python training." cheers, -wesley ps. a great big public THANKS to Rob Stephenson for putting together the short PodCast clip of one of our training sessions for your viewing pleasure on a video iPod or iTunes on your Mac! - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From tim at pollenation.net Thu Mar 30 08:25:36 2006 From: tim at pollenation.net (Tim Parkin) Date: Thu, 30 Mar 2006 14:25:36 +0100 Subject: New Python website, new documentation ? In-Reply-To: <1143647642.708869.250060@i39g2000cwa.googlegroups.com> References: <1143647642.708869.250060@i39g2000cwa.googlegroups.com> Message-ID: <442BDC50.6030306@pollenation.net> 1024nospam at freesurf.fr wrote: >Hi, > >I was wondering : as there has been a change in python.org website with >a new design, is it planned for the documentation section to be >revamped as well ? If yes, would it be just a appearance renewal or >would there also be changes in the doc itself ? > >Martin. > > docs.python.org will stay the same as far as I am aware but I'll be looking at trying out a version of the docs using the new python.org layout. Obviously this will affect more regular users of the site and so will need testing out first. The structure of the documentation won't change but it will have a new navigation (rather than just the back, up, forward on the current latex2html output). It's probably best to get something up on a test site to look at before over-analysing it though.. Tim Parkin From paul.dale at traxon.com Mon Mar 6 23:06:30 2006 From: paul.dale at traxon.com (paul.dale at traxon.com) Date: Tue, 7 Mar 2006 05:06:30 +0100 Subject: Checking function calls Message-ID: <20060307035304.57E083F4E@dftfe1.traxon.com> I will be out of the office from March 3rd to March 31st. In urgent cases please contact helpdesk at traxon.com From sullivanz.pku at gmail.com Sat Mar 11 08:10:46 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 11 Mar 2006 05:10:46 -0800 Subject: Can not find a file in CMD model python when everything is OK in IDLE In-Reply-To: References: <1142072665.951623.12350@j33g2000cwa.googlegroups.com> Message-ID: <1142082646.103488.108030@j33g2000cwa.googlegroups.com> I see. I once was a VB programmer. In VB, the current directory is always set to where the module locates before it runs. From scott.daniels at acm.org Thu Mar 2 13:12:25 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 02 Mar 2006 10:12:25 -0800 Subject: asynchat network send problems In-Reply-To: References: Message-ID: <440733b7$1@nntp0.pdx.net> Andreas R. wrote: > 4. In the found_terminator() method, the data is attempted to be > uncompressed, but it failes, since the received data does not have the > same size as the data which is sent. Sometimes, the difference in size > is often 512 between client and server, when running len(packet) on the > *compressed* packed. The len() of a large packet is usually about 64969. Just a guess, but do you know "send" and "receive" are not guaranteed to send all bytes or receive all bytes? The network itself is allowed to re-pack packets at any point in the path, and delays may happen at any packet boundary (including those boundaries created by the network). You need to do something like "sendall" and your receiver needs to know when it needs to wait for more data (as a matter of protocol design). -- -Scott David Daniels scott.daniels at acm.org From sjmachin at lexicon.net Mon Mar 20 07:01:59 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 20 Mar 2006 23:01:59 +1100 Subject: ANNOUNCE: xlrd 0.5.2 -- extract data from Excel spreadsheets In-Reply-To: <1142854637.666293.205330@u72g2000cwu.googlegroups.com> References: <441c7714$1_2@newspeer2.tds.net> <441C9F4D.1030203@lexicon.net> <441ccb61$1_3@newspeer2.tds.net> <441D23F2.7090808@lexicon.net> <1142850490.058912.138560@e56g2000cwe.googlegroups.com> <441E865D.20508@lexicon.net> <1142852445.087922.250140@g10g2000cwb.googlegroups.com> <441E8F48.6070404@lexicon.net> <1142854637.666293.205330@u72g2000cwu.googlegroups.com> Message-ID: <441E99B7.1050506@lexicon.net> On 20/03/2006 10:37 PM, jcmendez wrote: > Exactly. Yes, your requirement is exactly that, a list of references. > Once I get the formulas, I can do a weak parsing of them and > find the references. > A formula is not stored as input e.g. "(A1+A2)*3.0+$Z$29"; it's kept as an RPN stream of variable-length tokens. You don't need to parse it in the sense you were probably thinking of; *ALL* [ho ho chuckle chuckle] you need to do is step through the tokens and do something with the ones that contain references. Have a peek at this: http://sc.openoffice.org/excelfileformat.pdf -- formulas are covered in 40+ pages starting at about page 25. Cheers, John From tjreedy at udel.edu Wed Mar 29 21:51:07 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 29 Mar 2006 21:51:07 -0500 Subject: Try Python! References: <1143663801.542233.206500@u72g2000cwu.googlegroups.com><1143667470.851465.284830@i39g2000cwa.googlegroups.com> <1143675907.958211.253820@j33g2000cwa.googlegroups.com> Message-ID: "Michael Tobis" wrote in message news:1143675907.958211.253820 at j33g2000cwa.googlegroups.com... ... > I refer you in particular to these messages from BDFL: > > http://mail.python.org/pipermail/python-dev/2002-December/031246.html This one says that new style classes in 2.2 opened a new, sizable, security hole. One can avoid this by running 2.1. > http://mail.python.org/pipermail/python-dev/2002-December/031251.html This one says that he doubts that Python will ever reach a level of no security flaws. And that he does not want to spend his life just getting close. > > So what is the scoop? Why does Guido say there is no such thing as a > secure Python, and (as is generally reasonable) presuming he is correct > on the matter, how can these sites work safely? There are, of course, degrees of security. Any site can choose to operate with a lesser degree than Guido would accept for a 'secure Python' release. If I were running a publicly available site, I would run Python under *nix with someone with some security admin experience. I would use a dedicated machine from a few years ago not needed for anything else. I would have the full installation backed up on a bootable CD or DVD. I would expect most visitors to not pee in the fountain. And I would expect to have to reinstall occasionally when someone did. And I would at least remove all the net access and protocol modules and worry about making sure that the interpreter had no access to the system net resources so as to not be a vehicle for damaging other machines. Terry Jan Reedy From wkehowski at cox.net Sun Mar 26 15:13:02 2006 From: wkehowski at cox.net (wkehowski at cox.net) Date: 26 Mar 2006 12:13:02 -0800 Subject: wildcard exclusion in cartesian products Message-ID: <1143403982.717719.315360@i39g2000cwa.googlegroups.com> The python code below is adapted from a Haskell program written by Tomasz Wielonka on the comp.lang.functional group. It's more verbose than his since I wanted to make sure I got it right. http://groups.google.com/group/comp.lang.functional/browse_frm/thread... Does anyone know how to turn it into a module (or whatever it's called) so that I can put it in a loop and not have to generate the whole list? I've already tried without success. The program solves the following problem: generate the subset X of the cartesian product S^n that excludes n-tuples defined by wildcards. For example, if I want to exclude from [1,2,3]^3 the wc's [1,"*",2] and ["*",3,"*",3,"*"], where "*" stands for a sequence of zero or more elements of [1,2,3], then I just type for x in generateNotMatching([1,2,3,4],4,[[1,'*',2],[3,'*',4]]): print x and get the output [1, 1, 1] [1, 1, 3] [1, 2, 1] [1, 2, 3] [1, 3, 1] [2, 1, 1] [2, 1, 2] [2, 1, 3] [2, 2, 1] [2, 2, 2] [2, 2, 3] [2, 3, 1] [2, 3, 2] [3, 1, 1] [3, 1, 2] [3, 2, 1] [3, 2, 2] This is nice! But all elements are generated before they are printed. ##---------------------------- import sys, os, string def imap(function, source): for element in source: yield function(element) def any(iterable): '''True iff at least one element of the iterable is True''' for element in iterable: if element: return True # or element and change the definition return False def all(iterable): '''True iff no element of the iterable is True''' '''SHOULD BE?: True iff all element of the iterable are True''' for element in iterable: if not element: return False return True def rev(L): rL=[] for x in L: rL=[x]+rL return rL def advancePattern(x,p): if p==[]: return [] else: h=p[0] t=p[1:] if h != '*': if h == x: return [t] else: return [] else: return [p] + [t] + advancePattern(x,t) def advancePatterns(x,P): aP=[] for p in P: aP += advancePattern(x,p) return aP # return [advancePattern(x,p) for p in P] def allStar(p): return all( imap((lambda x: x=='*'),p) ) def notNullOrZero(p,n): return p !=[] or n==0 def generateNotMatching(A,n,P): return gen(A,n,P,[]) def gen(A,n,P,acc): if any(imap((lambda p: allStar(p) and notNullOrZero(p,n)), P)): return [] else: if n==0: return map(rev,[acc]) else: aG=[] for a in A: aG += gen(A,n-1,advancePatterns(a,P),[a]+acc) return aG ##---------------------------- From vincent at visualtrans.de Sun Mar 19 09:01:56 2006 From: vincent at visualtrans.de (Vincent Wehren) Date: Sun, 19 Mar 2006 14:01:56 -0000 Subject: Getting .NET SDK to work with Python 2.4.2 References: <1142721716.734835.157980@z34g2000cwc.googlegroups.com> <441D5181.2060103@v.loewis.de> <1142773131.890196.309940@i39g2000cwa.googlegroups.com> Message-ID: "Dave" wrote in message news:1142773131.890196.309940 at i39g2000cwa.googlegroups.com... | Well i don't have the whole visual studio. I don't have 7 either, I | have 8. I have VB and VC++ Express. If there is no way to download VS7, | could someone point me to directions on how to build the extensions | with mingw32? | I used the free MS Visual C++ Toolkit 2003 successfully to compile extenstions before I had access to VS. There's a how to here: http://www.vrplumber.com/programming/mstoolkit/ Regards, Vincent Wehren From sybrenUSE at YOURthirdtower.com.imagination Wed Mar 1 11:08:57 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 1 Mar 2006 17:08:57 +0100 Subject: PIL and PSDraw References: <1141223009.060268.90540@i39g2000cwa.googlegroups.com> Message-ID: Kjell Magne Fauske enlightened us with: > PIL is, as far as i know,primarily a tool for creating and > manipulating raster graphics. I was afraid of that. > If you want to create eps vector graphics with Python I recommend > PyX: That looks exactly what I was looking for. Thanks a lot! 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 antroy at gmail.com Fri Mar 10 05:31:16 2006 From: antroy at gmail.com (Ant) Date: 10 Mar 2006 02:31:16 -0800 Subject: Python Evangelism In-Reply-To: References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> Message-ID: <1141986676.542493.262590@z34g2000cwc.googlegroups.com> > It's not too late to rename the cheese shop though. > (We don't need even more stink...) What kind of cheese do you guys eat anyway ;-) It's not the names that are the problem as far as markleing goes - they are not dull names, which means they won't be forgotten. This is a good thing! As is the humour - who amongst us are going to forget where the repository for community projects are? Unlike RubyJewels, RubyBaubles or whatever ;-) As long as the names are memorable, marketing isn't an issue if it want's to be done. For example the famous British inventors Wallace and Gromit could be asked to endorse Python, ("Look Gromit - a Cheese shop!"). And there is a successful web-based credit card called an Egg card. A Python is a good powerful image to have associated with the language. What does Ruby say? That the language is pretty? And Perl? Misleading advertising there then ;-) Ever seen a Python? Powerful, elegant, and can digest just about anything you can feed it... good image I reckon! I'm obviously not suggesting we do such a thing, just pointing out a couple of things: 1) There's nothing wrong with the names we've got. 2) Some people on this newsgroup need to clean their fridges out more often! -- Ant... From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Tue Mar 14 05:04:33 2006 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Tue, 14 Mar 2006 11:04:33 +0100 Subject: Localized month names? In-Reply-To: References: Message-ID: <47niphFgg5kaU1@news.dfncis.de> Benji York schrieb: > Jarek Zgoda wrote: > >> How do I get a list of localized month names for current locale? The >> first thing that came to my mind was an ugly hack: > > >>>> import locale >>>> locale.nl_langinfo(locale.MON_1) > 'January' > What did you leave out? I get Traceback (most recent call last): File "", line 1, in -toplevel- locale.nl_langinfo(locale.MON_1) AttributeError: 'module' object has no attribute 'nl_langinfo' (Python 2.4, german Windows XP Pro) Moreover, 'January' is probably not localized. -- Dr. Sibylle Koczian Universitaetsbibliothek, Abt. Naturwiss. D-86135 Augsburg e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE From mnations at gmail.com Sat Mar 18 02:31:55 2006 From: mnations at gmail.com (Mudcat) Date: 17 Mar 2006 23:31:55 -0800 Subject: Using yacas within Python for symbolis computation In-Reply-To: <1142599604.967175.280800@z34g2000cwc.googlegroups.com> References: <1142599604.967175.280800@z34g2000cwc.googlegroups.com> Message-ID: <1142667115.602499.189230@v46g2000cwv.googlegroups.com> Out of curiosity, are you also Texas Longhorn JCDenton in another online life? From steve at hastings.org Mon Mar 27 14:16:05 2006 From: steve at hastings.org (Steve R. Hastings) Date: Mon, 27 Mar 2006 11:16:05 -0800 Subject: maximum() efficency References: <1143474600.972823.111570@i40g2000cwc.googlegroups.com> Message-ID: On Mon, 27 Mar 2006 07:50:01 -0800, Arne Ludwig wrote: > Just for completeness: The functions in Steve's original post named > maximum calculate the minimum. Er, yes. I benchmarked them but clearly I should have function-tested them as well. Here is, I hope, my last word on maximum(). It figures out whether it got an iterator or a list, and does the right thing. I believe it will compile and run correctly whether your version of Python has iterators or not. And, it doesn't compute the minimum. def maximum(cmp, seq): """ Return maximum value of seq, as chosen by provided cmp() function. If seq contains multiple maximal values, return the last one. Arguments: cmp -- function reference; function should return values with the same semantics as Python's cmp() function. seq -- any sequence (a list or an iterator). If seq is empty, this function will raise ValueError. """ # is it a list? if hasattr(seq, "__getitem__"): if len(seq) == 0: raise ValueError, "seq must contain at least 1 element" maxval = seq[0] for v in seq: if cmp(maxval, v) <= 0: maxval = v return maxval # is it an iterator? if hasattr(seq, "__iter__") and hasattr(seq, "next"): try: maxval = seq.next() except StopIteration: raise ValueError, "seq must contain at least 1 element" for v in seq: if cmp(maxval, v) <= 0: maxval = v return maxval raise TypeError, "seq must be a list or an iterator" -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From maxm at mxm.dk Mon Mar 27 06:56:52 2006 From: maxm at mxm.dk (Max M) Date: Mon, 27 Mar 2006 13:56:52 +0200 Subject: Difference between 'is' and '==' In-Reply-To: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> Message-ID: <4427d287$0$38669$edfadb0f@dread12.news.tele.dk> mwql wrote: > Hey guys, this maybe a stupid question, but I can't seem to find the > result anywhere online. When is the right time to use 'is' and when > should we use '=='? "is" is like id(obj1) == id(obj2) >>> 100+1 == 101 True >>> 100+1 is 101 False They don't have the same id. (Think of id as memory adresses.) -- 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 fredrik at pythonware.com Thu Mar 9 13:46:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 9 Mar 2006 19:46:20 +0100 Subject: About IDLE? References: Message-ID: "Dr. Pastor" wrote: > Installed Python 2.4.2 on Windows XP. > Activated IDLE. > Loaded the following into the Edit window: > --- > # dates are easily constructed and formatted (Tutorial 10.8) > > from datetime import date > now = date.today() > now > > now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") > > # dates support calendar arithmetic > > birthday = date(1985, 12, 1) > age = now - birthday > age.days > --- > When I select Run Module in the Edit window, I got only > two >>> after the RESTART line. > I expected to see the output of several commands! > Typing in age.days do produce the number of days. > > Why I do not get any output? while the interactive console echoes the result back if you type in an arbitrary expression, the interpreter doesn't do that if you run things in a script. to print stuff from a script, use the "print" statement. print now print now.strftime(...) ... print age.days your favourite tutorial (hopefully) contains more information about the interactive mode, and how it differs from code in scripts or modules. hope this helps! From skip at pobox.com Tue Mar 28 10:25:29 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 28 Mar 2006 09:25:29 -0600 Subject: doctest, unittest, or if __name__='__main__' In-Reply-To: <7xpsk7ch59.fsf@ruckus.brouhaha.com> References: <1142974528.143287.326360@e56g2000cwe.googlegroups.com> <1143512909.811663.32850@j33g2000cwa.googlegroups.com> <7xpsk7ch59.fsf@ruckus.brouhaha.com> Message-ID: <17449.21865.524355.692114@montanaro.dyndns.org> Paul> The unpythonicness stems from it being basically a Paul> reimplementation of JUnit, which was designed for use with Java. I think there are a few modules in Python which suffer that affliction. Skip From roy at panix.com Sat Mar 11 09:33:47 2006 From: roy at panix.com (Roy Smith) Date: Sat, 11 Mar 2006 09:33:47 -0500 Subject: why no block comments in Python? References: <_MCPf.1749$No6.40293@news.tufts.edu> <1141843360.140692.44180@i39g2000cwa.googlegroups.com> <1141843575.283242.239150@p10g2000cwp.googlegroups.com> <1142071008.571909.24210@v46g2000cwv.googlegroups.com> Message-ID: In article <1142071008.571909.24210 at v46g2000cwv.googlegroups.com>, "Jonathan Gardner" wrote: > Warby wrote: > > ...and I forgot to mention that the output of grep and diff is far more > > understandable in the absence of block comments! > > Which is why people do this /anyway/. (Kind of makes block comments > pointless, doesn't it? > > /* This is a > * really > * really > * long > * block comment */ Habit left over from the C days. It was the only way of making a block comment stand out visually. C++ has // comments, just like Python has #, but old habits die hard. From pommereau at univ-paris12.fr Mon Mar 20 11:54:19 2006 From: pommereau at univ-paris12.fr (Franck Pommereau) Date: Mon, 20 Mar 2006 17:54:19 +0100 Subject: Python / glade fundamentals In-Reply-To: <1142604240.110403.110560@v46g2000cwv.googlegroups.com> References: <1142604240.110403.110560@v46g2000cwv.googlegroups.com> Message-ID: <441edd77$0$10782$79c14f64@nan-newsreader-07.noos.net> > maybe you will find it easyer to use GladeGen to generate the > skeleton of your application rather then coding it yourself. Take a > look here: http://www.linuxjournal.com/article/7421 You may also use my PyGG module: http://freshmeat.net/projects/pygg Cheers, Franck From larry.bates at websafe.com Tue Mar 7 15:49:08 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 07 Mar 2006 14:49:08 -0600 Subject: Send email notification In-Reply-To: <1141759889.952367.59260@j33g2000cwa.googlegroups.com> References: <1141759889.952367.59260@j33g2000cwa.googlegroups.com> Message-ID: <440DF1C4.5030503@websafe.com> Ernesto wrote: > Is there a special module for mail ? > > I'd like to send an email [to 'n' unique email addresses] from a python > script. > > Thanks ! > This class makes what you want to do extremely easy. http://motion.sourceforge.net/related/send_jpg.py -Larry Bates From dmieluk at exemail.com.au Fri Mar 10 07:24:46 2006 From: dmieluk at exemail.com.au (Dave) Date: Fri, 10 Mar 2006 23:24:46 +1100 Subject: Speed of data structures in python Message-ID: Hi. I am learning PyOpenGL and I am working with a largish fixed scene composed of several thousand GLtriangles. I plan to store the coords and normals in a NumPy array. Is this the fastest solution in python? would i be significantly better off (timewise or otherwise) using some other data structure to hold this information? no other data structure appears as convenient, but am i loosing valuable time? I am new to 3d programming so please feel free to state the obvious, thanks. Dave. -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From florasol at hotmail.com Sun Mar 5 10:44:10 2006 From: florasol at hotmail.com (Francois) Date: 5 Mar 2006 07:44:10 -0800 Subject: Why I chose Python over Ruby Message-ID: <1141573450.667103.8930@z34g2000cwc.googlegroups.com> I discovered Python a few months ago and soon decided to invest time in learning it well. While surfing the net for Python, I also saw the hype over Ruby and tried to find out more about it, before I definitely embarked on studying and practicing Python. I recently found two sufficient answers for choosing Python - which is a personal choice and others may differ, but I'd like to share it anyway : 1) In Ruby there is a risk of "Variable/Method Ambiguity" when calling a method with no parameters without using () : Here is an excerpt from the book "Programming Ruby The Pragmatic Programmer's Guide". http://www.rubycentral.com/book/language.html "When Ruby sees a name such as ``a'' in an expression, it needs to determine if it is a local variable reference or a call to a method with no parameters. To decide which is the case, Ruby uses a heuristic. As Ruby reads a source file, it keeps track of symbols that have been assigned to. It assumes that these symbols are variables. When it subsequently comes across a symbol that might be either a variable or a method call, it checks to see if it has seen a prior assignment to that symbol. If so, it treats the symbol as a variable; otherwise it treats it as a method call. As a somewhat pathological case of this, consider the following code fragment, submitted by Clemens Hintze." def a print "Function 'a' called\n" 99 end for i in 1..2 if i == 2 print "a=", a, "\n" else a = 1 print "a=", a, "\n" end end OUTPUTS >> a=1 Function 'a' called a=99 "During the parse, Ruby sees the use of ``a'' in the first print statement and, as it hasn't yet seen any assignment to ``a,'' assumes that it is a method call. By the time it gets to the second print statement, though, it has seen an assignment, and so treats ``a'' as a variable. Note that the assignment does not have to be executed---Ruby just has to have seen it. This program does not raise an error." I tried the code above at the interactive Ruby 1.8.2 interpreter : http://www.ruby.ch/tutorial/ 2) Ruby does not have true first-class functions living in the same namespace as other variables while Python does : In Python : def sayHello (name) : return "Hello " + name print sayHello("Mr. Bond") m = sayHello print m print m("Miss Moneypenny") OUTPUTS >> Hello Mr. Bond Hello Miss Moneypenny In Ruby you need extra syntax that ruins the "first-class-ness" : def sayHello (name) return "Hello " + name end puts sayHello("Mr. Bond") m = Class.method(:sayHello) puts m puts m.call("Miss Moneypenny") OUTPUTS >> Hello Mr. Bond # Hello Miss Moneypenny 4) Conclusion Since I did a lot of work in Scheme, rigor and consistency are most important to me, and Python certainly meets this requirement. --- Python newbie From sudharsh at gmail.com Sat Mar 18 03:01:43 2006 From: sudharsh at gmail.com (sudharsh at gmail.com) Date: 18 Mar 2006 00:01:43 -0800 Subject: Writing web bots in python Message-ID: <1142668903.336769.184570@u72g2000cwu.googlegroups.com> Hello, I hav a question..How do I write a webbot that logs onto some website, fills text into a textbox and submit that form, Sorry I am a novice in python, apparently I have to use urllib, but I hav a few queries on this, What happens when there are more input interfaces..does urllib make somekind of a template when it does so..need more info on this..links and tutorilas would be appreciated..thanx Sudharshan S From python at rcn.com Sun Mar 12 20:56:37 2006 From: python at rcn.com (Raymond Hettinger) Date: 12 Mar 2006 17:56:37 -0800 Subject: "RuntimeError: dictionary changed size during iteration" ; Good atomic copy operations? References: Message-ID: <1142214997.549342.123440@e56g2000cwe.googlegroups.com> [robert] > In very rare cases a program crashes (hard to reproduce) : > > * several threads work on an object tree with dict's etc. in it. Items > are added, deleted, iteration over .keys() ... ). The threads are "good" > in such terms, that this core data structure is changed only by atomic > operations, so that the data structure is always consistent regarding > the application. Only the change-operations on the dicts and lists > itself seem to cause problems on a Python level .. > > * one thread periodically pickle-dumps the tree to a file: > >>> cPickle.dump(obj, f) > > "RuntimeError: dictionary changed size during iteration" is raised by > .dump ( or a similar "..list changed ..." ) > > What can I do about this to get a stable pickle-dump without risiking > execution error or even worse - errors in the pickled file ? > > Is a copy.deepcopy ( -> "cPickle.dump(copy.deepcopy(obj),f)" ) an > atomic opertion with a guarantee to not fail? No. It is non-atomic. It seems that your application design intrinsically incorporates a race condition -- even if deepcopying and pickling were atomic, there would be no guarantee whether the pickle dump occurs before or after another thread modifies the structure. While that design smells of a rat, it may be that your apps can accept a dump of any consistent state and that possibly concurrent transactions may be randomly included or excluded without affecting the result. Python's traditional recommendation is to put all access to a resource in one thread and to have other threads communicate their transaction requests via the Queue module. Getting results back was either done through other Queues or by passing data through a memory location unique to each thread. The latter approach has become trivially simple with the advent of Py2.4's thread-local variables. Thinking about future directions for Python threading, I wonder if there is a way to expose the GIL (or simply impose a temporary moratorium on thread switches) so that it becomes easy to introduce atomicity when needed: gil.acquire(BLOCK=True) try: #do some transaction that needs to be atomic finally: gil.release() > Or can I only retry several times in case of RuntimeError? (which would > apears to me as odd gambling; retry how often?) Since the app doesn't seem to care when the dump occurs, it might be natural to put it in a while-loop that continuously retries until it succeeds; however, you still run the risk that other threads may never leave the object alone long enough to dump completely. Raymond From sullivanz.pku at gmail.com Thu Mar 9 15:33:58 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 9 Mar 2006 12:33:58 -0800 Subject: Any python HTML generator libs? Message-ID: <1141936438.584242.129220@z34g2000cwc.googlegroups.com> Hi, everyone. Simply put, what I need most now is a python lib to generate simple HTML. I am now using XML to store my lab report records. I found python really convinient to manipulate XML, so I want to make a small on-line CGI program to help my colleagues to build their lab report records into XML, for storage, HTML display (for others to browse) and search. With python's standard lib, the DOM object could realize the XML storage and search quite easily, but for HTML generation, it is a great headache. I tried to turn to the in-line server-side python script PSP(something like asp and php) instead of CGI. However, since the report data is always of very complex data structures, it is really hard to write most things in-line. For example, a PCR reaction is expected to be shown in this format or alike on a web browser: PCR Sample: Sm1032 Operater: SullivanZ TimeStamp: hh:mm mm-dd-yyyy Reaction: Reagent1: Name:XXXX Concentration:XXXX mM Volumn:XXX uL Reagent2: ........................ ........................ Since there are hundreds of PCR reaction and other operations in the lab report, in-line PSP is not a suitable solution. But writing HTML directly with print statement is a great pain. Will XSTL be useful? Is my problem somewho related with XML-SIG? Looking forward to your precious suggestion. From deets at nospam.web.de Mon Mar 6 12:42:47 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 06 Mar 2006 18:42:47 +0100 Subject: Need help initializing a list or tuple. In-Reply-To: <1141666188.237150.320690@j52g2000cwj.googlegroups.com> References: <1141664498.539402.43160@e56g2000cwe.googlegroups.com> <1141666188.237150.320690@j52g2000cwj.googlegroups.com> Message-ID: <473aknFdkti4U1@uni-berlin.de> KraftDiner schrieb: > Thank you that worked great! > > a = [[None] * 256] * 256 > for i in range(0,256): > for j in range(0,256): > a[i][j] = i**2 > > Now.. Can I change this quickly into a 1 dimensional list of length > 65536? sum(a, []) Diez From steven.bethard at gmail.com Sun Mar 19 00:34:03 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 18 Mar 2006 22:34:03 -0700 Subject: strange math? In-Reply-To: <1142745707.384085.42050@i39g2000cwa.googlegroups.com> References: <1142745707.384085.42050@i39g2000cwa.googlegroups.com> Message-ID: joe.hrbek at gmail.com wrote: >>>> f(01) > 43 >>>> f(02) > 44 >>>> f(010) > 50 >>>> 42+010 > 50 > > The first f(01) was a mistake. I accidentally forgot to delete the > zero, but to my suprise, it yielded the result I expected. So, I tried > it again, and viola, the right answer. So, I decided to really try and > throw it for a loop, f(010), and it produced 50. I expected 52 > (42+10). Why doesn't python ignore the first zero and produce a result > of 52? It ignored the first zero for f(01) and f(02). Hmm. I know, I > know, why am I sending it a 01,02, or a 010 to begin with? Like I > said, it was an accident, but now i'm curious. I'm not a computer > science major so please be kind with any explanations. Python isn't ignoring the initial 0. It reads the initial 0 as indicating that the following number is expressed in octal. You can see this if you try any number with a digit higher than 7 in it: >>> 08 Traceback ( File "", line 1 08 ^ SyntaxError: invalid token So you get 8 added to your number when you write 010 because eight is spelled as 10 in octal. The leading-zero notation is unfortunate, and there has been some recent discussion[1][2] on python-dev about trying to change the prefix to ``0o`` or ``0c`` in Python 3.0 but for the moment at least it looks like we're stuck with the confusing leading zero. [1]http://mail.python.org/pipermail/python-dev/2006-January/060262.html [2]http://mail.python.org/pipermail/python-dev/2006-February/060277.html STeVe From jbenson at sextans.lowell.edu Sun Mar 26 21:17:51 2006 From: jbenson at sextans.lowell.edu (Jim Benson) Date: Sun, 26 Mar 2006 19:17:51 -0700 (MST) Subject: How to learn python if I'm very familar with C++ In-Reply-To: <1143425213.085645.146410@u72g2000cwu.googlegroups.com> Message-ID: On 26 Mar 2006, PengYu.UT at gmail.com wrote: > Hi, > > I've been using C++ for a few years and have developed a few projects > in C++. And I'm familar with OO and template metaprogramming. > > There are some book like "Learning Perl". It is a little bit tedious > for me, because more material in that book seems obvious for me. I want > some book describe the difference between C++ and python such that I > could grasp python quickly. Would you please give me some infomation on > this? > > Thanks, > Peng > > The book "Learning Python" worked for me (a long time C++ person). Jim From joemynz at gmail.com Thu Mar 9 23:05:55 2006 From: joemynz at gmail.com (joemynz at gmail.com) Date: 9 Mar 2006 20:05:55 -0800 Subject: urlerror, urllib2: "no address" ... why or debug tips? Message-ID: <1141963555.362124.38520@j52g2000cwj.googlegroups.com> Help please with a URLError. Invoking a url that works in Firefox and IE results in a "urlerror 7, no address ..." in python. I need to debug why. Traceback is below. There's a redirect when the url is invoked (it's part of a chain) - you can see it using liveheaders in firefox. What is the best way to debug this? I tried setting debug on HTTPConnection but this doesn't work (from some web posts, setting debug is broken in 2.4). What's the best way to see what's happening, way to monitor the call sequences etc? Any help much appreciated. Thx. handle = urllib2.urlopen(req) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 130, in urlopen return _opener.open(url, data) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 364, in open response = meth(req, response) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 471, in http_response response = self.parent.error( File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 396, in error result = self._call_chain(*args) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 337, in _call_chain result = func(*args) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 554, in http_error_302 return self.parent.open(new) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 358, in open response = self._open(req, data) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 376, in _open '_open', req) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 337, in _call_chain result = func(*args) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 1021, in http_open return self.do_open(httplib.HTTPConnection, req) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/urllib2.py", line 996, in do_open raise URLError(err) URLError: From aleaxit at yahoo.com Sat Mar 4 12:08:22 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Mar 2006 09:08:22 -0800 Subject: Python advocacy in scientific computation References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> Message-ID: <1hbo3wz.1ab4ucl11f31enN%aleaxit@yahoo.com> Terry Hancock wrote: > In fact, if I had one complaint about Python, it was the > "with a suitable array of add-ons" caveat. The proprietary > alternative had all of that rolled into one package (abeit > it glopped into one massive and arcane namespace), whereas > there was no "Python Data Language" or whatever that > would include all that in one named package that everyone > could recognize (I suppose SciPy is trying to achieve that). I believe the Enthought distribution of Python (for Windows, with a Mac version planned) is trying to move exactly in that direction, by packaging up everything and a half (while of course leaving a reasonable assignment of namespaces from the pieces it's packaging!-). However, maintaining such a distro, and making it available for a wider variety of platforms, are heavy, continuing tasks -- unless either firms, such as Enthought, or volunteers, commit to such tasks, they won't "just happen". Alex From brian at sweetapp.com Mon Mar 27 07:05:50 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 27 Mar 2006 14:05:50 +0200 Subject: XMLRPCServer issues In-Reply-To: <1143454964.071222.304540@e56g2000cwe.googlegroups.com> References: <1143454964.071222.304540@e56g2000cwe.googlegroups.com> Message-ID: <4427D51E.1000500@sweetapp.com> 1. Is there on option to get cx_Oracle to return string data as unicode rather than strings objects? XML-RPC aside, dealing with unicode objects might be better than dealing with encoded strings. 2. You might want to transmit integers as strings rather than use the XML-RPC integer type (which is limited to numbers between -2147483648 and 2147483647). Cheers, Brian From nospamformeSVP at gmail.com Mon Mar 13 08:49:29 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Mon, 13 Mar 2006 08:49:29 -0500 Subject: Python IDE: great headache.... In-Reply-To: References: <1142120002.912902.69630@i40g2000cwc.googlegroups.com> Message-ID: Joel Hedlund wrote: >> If you install Eclipse and try to use it without reading the >> Workbench User Guide then you are not going to get anywhere. > > > Woah, easy now! I never read any "Workbench User Guide" and I'm doing > just fine with PyDev. Fabio Zadrozny (PyDev developer) wrote an > excellent startup guide for python programmers that includes > installing and basic editing: > > http://www.fabioz.com/pydev/manual_101_root.html > > It's all I ever read and it was enough for me to get going with > Eclipse + PyDev within 15 minutes on a WinXP machine. > Sorry to offend, I was just extrapoloating from personal experience. When I was looking for a Java IDE I tried IntelliJ Idea, Netbeans and Eclipse in that order. I found that I could use Idea and Netbeans without reading the manuals, but I could not get going with Eclipse until I read the Workbench User Guide and got the hang of perspectives and views. Even installing it the first time seemed to be a mystery. It is not difficult at all, just different. In retrospect, I don't know why I found it puzzling but I have met others who have had the same experience. It has improved a lot recently, but even the Eclipse web-site was hard to navigate. I think that a lot of the puzzlement comes from the fact that the Eclipse folks present Eclipse not as an IDE, but as a framework where one of the applications happens to be an IDE. Don. From danbrwn at gmail.com Wed Mar 29 15:15:31 2006 From: danbrwn at gmail.com (Dan) Date: 29 Mar 2006 12:15:31 -0800 Subject: COM callbacks in Python In-Reply-To: <1143213084.417506.162960@e56g2000cwe.googlegroups.com> References: <1143148427.605756.205120@g10g2000cwb.googlegroups.com> <1143181153_2597@sp6iad.superfeed.net> <1143211601.571662.255100@j33g2000cwa.googlegroups.com> <1143213084.417506.162960@e56g2000cwe.googlegroups.com> Message-ID: <1143663331.769153.236110@j33g2000cwa.googlegroups.com> One final note, The code posted does work. Unfortunately, the event only fires for the ADO connection who actually triggered the event. In my opinion, completely useless event. So the Python worked, The ADO does not do what its name implies. Thanks to all. Dan From jdhunter at ace.bsd.uchicago.edu Thu Mar 16 10:56:00 2006 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 16 Mar 2006 09:56:00 -0600 Subject: Computing correlations with SciPy References: <1142524171.358429.129850@i39g2000cwa.googlegroups.com> Message-ID: <87wteu8ju7.fsf@peds-pc311.bsd.uchicago.edu> >>>>> "tkpmep" == tkpmep writes: tkpmep> I want to compute the correlation between two sequences X tkpmep> and Y, and tried using SciPy to do so without success.l tkpmep> Here's what I have, how can I correct it? >>>> X = [1, 2, 3, 4, 5] Y = [5, 4, 3, 2, 1] import scipy >>>> scipy.corrcoef(X,Y) tkpmep> Traceback (most recent call last): File " input>", line 1, in ? File tkpmep> "C:\Python24\Lib\site-packages\numpy\lib\function_base.py", tkpmep> line 671, in corrcoef d = diag(c) File tkpmep> "C:\Python24\Lib\site-packages\numpy\lib\twodim_base.py", tkpmep> line 80, in diag raise ValueError, "Input must be 1- or tkpmep> 2-d." ValueError: Input must be 1- or 2-d. >>>> Hmm, this may be a bug in scipy. matplotlib also defines a corrcoef function, which you may want to use until this problem gets sorted out In [9]: matplotlib.mlab.corrcoef(X,Y) In [10]: X = [1, 2, 3, 4, 5] In [11]: Y = [5, 4, 3, 2, 1] In [12]: matplotlib.mlab.corrcoef(X,Y) Out[12]: array([[ 1., -1.], [-1., 1.]]) From msoulier at gmail.com Mon Mar 27 08:55:21 2006 From: msoulier at gmail.com (msoulier) Date: 27 Mar 2006 05:55:21 -0800 Subject: Module documentation In-Reply-To: <4426de00$0$24263$636a55ce@news.free.fr> References: <4426de00$0$24263$636a55ce@news.free.fr> Message-ID: <1143467721.030719.107720@g10g2000cwb.googlegroups.com> Bruno Desthuilliers wrote: > In the python shell, typing 'help()' should get you started most > of the time. And honestly, it should work all of the time. If it doesn't, file a bug report. I can't stand it when that doesn't work. Some of us don't do all of our work with a browser handy, and a net connection. Mike From mtobis at gmail.com Mon Mar 20 20:04:45 2006 From: mtobis at gmail.com (Michael Tobis) Date: 20 Mar 2006 17:04:45 -0800 Subject: New-style Python icons In-Reply-To: <1142902321.251730.210540@u72g2000cwu.googlegroups.com> References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> <441ee5e7$1@nntp0.pdx.net> <1142890518.478461.31610@e56g2000cwe.googlegroups.com> <1142899846.158835.42810@e56g2000cwe.googlegroups.com> <1142902321.251730.210540@u72g2000cwu.googlegroups.com> Message-ID: <1142903085.446579.172710@i39g2000cwa.googlegroups.com> OK, but Python IS clever, so its logo ought to be too. Since you are acknowledging they are tadpoles, I guess you've heard my gripes... mt From webraviteja at gmail.com Wed Mar 22 23:43:55 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 22 Mar 2006 20:43:55 -0800 Subject: need SOAPpy help In-Reply-To: References: Message-ID: <1143089035.424005.286460@e56g2000cwe.googlegroups.com> Did you read http://diveintopython.org/soap_web_services/index.html ? and specifically http://diveintopython.org/soap_web_services/introspection.html ? These docs are slightly dated but I doubt much has changed. If there is a problem, you can always try the older version from the site. From steve at REMOVETHIScyber.com.au Tue Mar 14 06:14:39 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 14 Mar 2006 22:14:39 +1100 Subject: Accessing overridden __builtin__s? References: <1142311784.996095.158950@j33g2000cwa.googlegroups.com> Message-ID: On Mon, 13 Mar 2006 21:28:06 -0800, garyjefferson123 wrote: > I'm having a scoping problem. I have a module called SpecialFile, > which defines: > > def open(fname, mode): > return SpecialFile(fname, mode) This is called "shadowing a built-in", and generally speaking it causes Bad Things To Happen. The secret to avoiding those Bad Things is to not shadow built-ins. This isn't a hard and fast rule, but as a good general principle, if you have to ask "How do I avoid this problem?", you shouldn't be using shadowing. (Think of it this way: if you have to ask "How do I avoid being horribly injured when I crash my car into a wall at 90mph?", you shouldn't be crashing your car into a wall at 90mph. Yes, I know that makes the bootstrapping problem difficult for those budding stunt men and women who want to learn, but they generally manage. And most of the time they manage by not actually crashing their car into a wall at 90mph -- they find a better way to get the same effect.) > class SpecialFile: > > def __init__(self, fname, mode): > self.f = open(fname, mode) > ... > > > The problem, if it isn't obvioius, is that the open() call in __init__ > no longer refers to the builtin open(), but to the module open(). In your code, open() is not a module, it is a function. A better technique will be to turn open into a method of the class SpecialFile, rather than a bare function. That way you keep open() the built-in function separate from SpecialFile.open(). > So, if I do: > > f = SpecialFile.open(name, mode) > > I get infinite recursion. I see you are already using an open method. So let me see if I have this right: you have a function open, plus an open method? Why? As near as I can tell, you have a function called "open" which returns a SpecialFile instance. I don't understand why you would want to do that -- it seems like a poor API design to me. But maybe there's something I don't understand. It looks like you are expecting to do this: file = open('data.txt', 'r') # file is now an automatically opened SpecialFile. This is bad design because it isn't clear that you have done something special. It *looks* like you have just opened an ordinary file, and unless you study the entire module, you wouldn't have any clue that in fact you have opened a SpecialFile instead. I would handle it like this: class SpecialFile(object): def __init__(self, fname, mode='r'): self.fname = fname self.mode = mode def open(self): self.f = open(self.fname, self.mode) def close(self): self.f.close() def read(self): return self.f.read() def write(self, data): self.f.write(data) You use it like so: sf = SpecialFile("hello.txt") sf.open() data = sf.read() sf.close() (Actually, I wouldn't handle it like this at all, unless a SpecialFile did things that an ordinary file didn't. But presumably you have something special in mind.) This, in my opinion, is a better solution. You don't have to jump through hoops to get back at the built-in version of open, and the code is self-documenting: to open a SpecialFile, you ask for a SpecialFile. -- Steven. From reply.in.the.newsgroup at my.address.is.invalid Fri Mar 3 09:39:05 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 03 Mar 2006 15:39:05 +0100 Subject: socket freezes References: <46qtqqFcej8bU1@individual.net> Message-ID: Luis P. Mendes: >I've developed a program that uses a socket to receive information 24h a >~ day. > >The problem is that the socket seems to freeze. By that I mean the >program stops getting information but doesn't raise any error. That's weird. There's probably a bug in your program. >I tried to solve this by writing the following functions, in order to >try to start the socket connection again: So now you have two problems. When there's a bug in your program, it's usually best to hunt it down, rather than to add more code with more bugs :-) -- Ren? Pijlman From google at al-got-rhythm.net Tue Mar 14 05:17:54 2006 From: google at al-got-rhythm.net (jalanb) Date: 14 Mar 2006 02:17:54 -0800 Subject: Is this possible in Python? In-Reply-To: <1142282467.270698.142780@p10g2000cwp.googlegroups.com> References: <1142238871.199749.243470@p10g2000cwp.googlegroups.com> <1142282467.270698.142780@p10g2000cwp.googlegroups.com> Message-ID: <1142331474.355167.20970@i40g2000cwc.googlegroups.com> You might like the version here: http://www.jorendorff.com/toys/out.html Especially the "need to know" presentation, which is cute -- Alan http://aivipi.blogspot.com From jstroud at ucla.edu Sun Mar 26 19:02:01 2006 From: jstroud at ucla.edu (James Stroud) Date: Sun, 26 Mar 2006 16:02:01 -0800 Subject: Python float representation error? In-Reply-To: <1143416404.380648.181190@t31g2000cwb.googlegroups.com> References: <1143416404.380648.181190@t31g2000cwb.googlegroups.com> Message-ID: mailpitches at email.com wrote: > try running this in python: > > print [39.95] > > the output i get is: > [39.950000000000003] > > what's up with that? > This comes from the imprecision in representing base-10 fractions as binary. Try "print [str(39.95)]". If you want to print a list, maybe: print map(str, alist) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From msoulier at gmail.com Wed Mar 8 09:09:17 2006 From: msoulier at gmail.com (msoulier) Date: 8 Mar 2006 06:09:17 -0800 Subject: Type Hinting vs Type Checking and Preconditions In-Reply-To: References: Message-ID: <1141826957.934692.289430@i40g2000cwc.googlegroups.com> > It's actually something that has been being considered for Python 3.0 > for a long time. I will never understand why we can't just leave a good language alone, and instead keep trying to make it everything for all people. If I want strong typing, I'll use Java or C++. And don't tell me to just "not use it", because the more that's added to the core language, the harder it becomes to inherit code, the ease of which being something that Python is supposed to stand for. Mike Soulier From godoy at ieee.org Thu Mar 23 09:13:41 2006 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 23 Mar 2006 11:13:41 -0300 Subject: Breaking/Wrapping lines "automatically" References: <877j6ll3i1.fsf@ieee.org> <87d5gdjlwh.fsf@ieee.org> Message-ID: <878xr1jlka.fsf@ieee.org> Jorge Godoy writes: > Then I'd have to have some means to determine the width of the char (I'm using > a TrueType font due to my need of using Unicode text) to calculate how many > words I can put on a single line... Hmmm... It looks like your code does that! Thanks! I'll give it a try here. -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From cfbolz at googlemail.com Thu Mar 9 07:37:44 2006 From: cfbolz at googlemail.com (cfbolz at googlemail.com) Date: 9 Mar 2006 04:37:44 -0800 Subject: implementation of "complex" type References: <1141895757.128437.159460@i39g2000cwa.googlegroups.com> Message-ID: <1141907864.393055.99870@v46g2000cwv.googlegroups.com> Hi! Russ wrote: > I tried the following: > > >>> x = complex(4) > >>> y = x > >>> y *= 2 > >>> print x, y > (4+0j) (8+0j) > > But when I tried the same thing with my own class in place of > "complex" above, I found that both x and y were doubled. I'd like to > make my class behave like the "complex" class. Can someone tell me the > trick? Also, where can I find the code for for the "complex" class? I > hope it's written in Python! Thanks. In CPython it is actually written in C, implemented in the Objects/complexobject.c file. See for example: http://svn.python.org/view/python/trunk/Objects/complexobject.c?rev=42596&view=markup In PyPy it is indeed a pure Python implementation right now: http://codespeak.net/svn/pypy/dist/pypy/module/__builtin__/app_complex.py Cheers, Carl Friedrich Bolz From edbiano at rocketmail.com Wed Mar 15 01:20:02 2006 From: edbiano at rocketmail.com (Eduardo Biano) Date: Tue, 14 Mar 2006 22:20:02 -0800 (PST) Subject: problem writing to a file each record read Message-ID: <20060315062002.25946.qmail@web34603.mail.mud.yahoo.com> I am a python newbie and I have a problem with writing each record read to a file. The expected output is 10 rows of records, but the actual output of the code below is only one row with a very long record (10 records are lump into one record). Thank you in advance for your help. Here is the code: **************************************** infile = open('c:/grad3650txt.csv', 'r') outfile = open('c:/idmast01.txt', 'w') a = 1 b = 10 for line in infile.readlines(): if a <= b: c1 = line.find(',',0) ln = line[1:c1] l2 = line.find('"', c1) l2a = l2 - 1 l2c = l2 if line[l2a] == '.': l2b = l2 - 3 if line[l2b] == ' ': mi = line[l2b+1:l2a+1] l2c = l2b else: mi = ' ' l2c = l2 fn = line[c1+2:l2c] c2 = line.find(',', l2) c3 = line.find(',', c2+1) deg = line[c2+1:c3] l5 = len(line) c4 = line.find(',', c3+1) l7 = c3 + 14 if l5 <= l7 or c4 <= l5: l8 = l5 if c4 <= l5: dat = line[c3+1:c4] #----------------------------------- # This is the problem code. Ten records # is lump into 1 row and written # in the output file. # # My expected output is 10 rows. #----------------------------------- info = string.join([fn, mi, ln, deg, dat] outfile.write(info) #---------------------------------- # a = 1 + a else: a = 1 + a infile.close() outfile.close() # ------------------------------------------------ Thank you very much for your help. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From phpbird at gmail.com Sat Mar 18 08:16:38 2006 From: phpbird at gmail.com (JuHui) Date: 18 Mar 2006 05:16:38 -0800 Subject: How to convert In-Reply-To: <1142687566.540612.83480@z34g2000cwc.googlegroups.com> References: <1142687566.540612.83480@z34g2000cwc.googlegroups.com> Message-ID: <1142687798.038654.12460@i39g2000cwa.googlegroups.com> >>> 10/3.0 3.3333333333333335 >>> int(10/3.0) 3 From fake at nospam.no Mon Mar 6 20:09:17 2006 From: fake at nospam.no (Blackbird) Date: Tue, 7 Mar 2006 02:09:17 +0100 Subject: %r References: <75-dnc5y7fLN-ZHZRVnzvA@telenor.com> <76WdnakbMbHG45HZ4p2dnA@telenor.com> Message-ID: Blackbird skrev: >> > Is the interpreter in fact using repr(), or parts of it, to generate > output when you type an expression at the command prompt? The > results sure look similar. Let me clarify this: The interpreter uses eval. No doubt about that. But >>> eval('f') >>> repr(f) '' So there is still a connection between eval and repr that I don't fully understand, besides the fact that eval (among other things) is the inverse of repr. Do they share some code, and if so, what part? Well, I guess I could of course take a few weeks off and dive into the source... not sure my wife would approve.. From sybrenUSE at YOURthirdtower.com.imagination Fri Mar 10 10:11:37 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 10 Mar 2006 16:11:37 +0100 Subject: Numbers in python References: <1142001687.621551.184000@i40g2000cwc.googlegroups.com> Message-ID: brainy_muppet at hotmail.com enlightened us with: > if I put 'THE' = float(0.965) it returns 0.96555555549 or something > similar. That's for the same reasons as you can't write 1/3rd in decimal notation. Computers can't write 1/10th in binary notation. 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 Fri Mar 10 11:31:57 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 10 Mar 2006 17:31:57 +0100 Subject: why use special config formats? References: <1142002082.976945.261900@e56g2000cwe.googlegroups.com> <1142004363.863051.29090@j33g2000cwa.googlegroups.com> Message-ID: tomerfiliba at gmail.com enlightened us with: > if you are really so scared of letting others exploit your config > scripts, then use the second, pickled fashion. that way you can > store the file at $HOME/blah-config.pkl, and everybody's happy. Ehm... and how is a user supposed to edit that? I wouldn't be happy... > still, my point is we dont need special config mechanisms, since the > builtin ones, like object persistency (sp) or python scripts are > good enough, less buggy, and dont require you to learn thousands of > config formats. Oh, and the ConfigParser module requires you to learn *thousands* of config formats. Right. I think you need to get real. 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 lists at elehack.net Sat Mar 11 19:08:21 2006 From: lists at elehack.net (Michael Ekstrand) Date: Sat, 11 Mar 2006 18:08:21 -0600 Subject: Which GUI toolkit is THE best? In-Reply-To: <1jk98ti5l75jq$.185esrz0xojp3$.dlg@40tude.net> References: <441172c2$1@news1.ethz.ch> <1jk98ti5l75jq$.185esrz0xojp3$.dlg@40tude.net> Message-ID: <20060311180821.bb56f9b7.lists@elehack.net> On Sat, 11 Mar 2006 00:07:52 +0100 Alan Franzoni wrote: > > again to make a choice is difficult; is there also some guy liking > > pyqt is it worse or should it be avoided because of the licencing > > policy for qt (which I also like..)? > > > > * Which one is the most fun to program with? > > * Which one is the most easy to learn? > > * Which one looks best? > > * Which one is the most productive to program with? > > wxPython is a pretty good 'all-round' and cross-platform library, and > includes some non-graphical features. It's got a drawback: it's a > wrapper for the wxwidgets library, and hence it's not very pythonic; > you can solve part of its unpythonicness using wax, which is not very > well documented at the time. wxGlade can be used to design GUI apps > with little effort. > > pyGTK works well, too. Recent versions perform well and are good > looking on Windows systems as well as Linux and Macs (if you provide > an X server). It's very well documented (better than wxPython, in my > opinion) and its license is quite permissive. It's unpythonic just > like wxPython. Glade and Gazpacho can be used to design GUI apps in a > visual way. I'll throw my two cents in here now. I've used both wxPython and PyGTK. I find wxPython to be horribly un-pythonic; combining that some problems on the Mac, and some other installation/environment issues, I ditched it for PyGTK. I find PyGTK to be very natural, and actually highly Pythonic. So much of its design just makes sense. And GTK provides a lot of nice things, and is itself incredibly versitle (the places you can put odd widgets...). I've found myself to be more productive with GTK (both PyGTK and GTKmm) than with any other system I've used (with the possible exception of web interfaces). - Michael -- mouse, n: a device for pointing at the xterm in which you want to type. -- Fortune From smitty_one_each at bigfoot.com Tue Mar 14 21:21:22 2006 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Tue, 14 Mar 2006 21:21:22 -0500 Subject: Cheese Shop: some history for the new-comers--Gratuitous self-quote References: <44126523$0$1016$afc38c87@news.optusnet.com.au> Message-ID: <87wtew4fdp.fsf@bigfoot.com> http://it.slashdot.org/article.pl?sid=05/08/01/0150222 Customer: Well, then, have you got any Venezuelan Beaver Cheese? Owner: Sir, this is a self-respecting establishment. I shall thank you not to imply we should traffic in VB, much less, even mention the foul product. Props, Chris From ruby at no.spam Fri Mar 10 12:18:18 2006 From: ruby at no.spam (Michal Kwiatkowski) Date: Fri, 10 Mar 2006 18:18:18 +0100 Subject: Why property works only for objects? In-Reply-To: <1hbyfme.1cul2uwko9576N%aleaxit@yahoo.com> References: <1hbyfme.1cul2uwko9576N%aleaxit@yahoo.com> Message-ID: Alex Martelli napisa?(a): >> So another question arise. Is it possible to make function a method (so >> it will receive calling object as first argument)? > > Sure, impor types then call types.MethodType: > > f = types.MethodType(f, obj, someclass) > > (f.__get__ is also fine for Python-coded functions) -- make sure that > someclass is obj's class or some ancestor of it, of course. I wasn't aware of types module. Thanks for your reply. 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 stanc at al.com.au Thu Mar 23 09:41:15 2006 From: stanc at al.com.au (Astan Chee) Date: Fri, 24 Mar 2006 01:41:15 +1100 Subject: python/py2exe running in background Message-ID: <4422B38B.3080000@al.com.au> Hi, Im using py2exe to convert my python scripts to .exe. Im trying to get my scripts and .exes to only run (utilize full CPU) when my PC is idle (kinda like SETI at home). Do i only need to modify GIL parameters or is there more to acomplishing this? Thanks From barmenkov at bpc-dot-ru.no-spam.invalid Wed Mar 15 04:42:58 2006 From: barmenkov at bpc-dot-ru.no-spam.invalid (PyDenis) Date: 15 Mar 2006 09:42:58 GMT Subject: details References: <4417d37c$0$76222$892e7fe2@authen.yellow.readfreenews.net> Message-ID: <4417e1a2$0$76792$892e7fe2@authen.yellow.readfreenews.net> Python: ActivePython 2.4.2 Build 10 (ActiveState Corp.) based on Python 2.4.2 (#67, Jan 17 2006, 15:36:03) [MSC v.1310 32 bit (Intel)] on win32 ------------------------- win32ui: Dont know how to get version info. Little snippet [code:1:f18a50c332]import win32ui aa = sorted(dir(win32ui)) for i in aa: print '%s => %r' % (i, getattr(win32ui, i)) print [/code:1:f18a50c332] gives me only copyright => 'Copyright 1994-2004 Mark Hammond (mhammond at skippinet.com.au)' ------------------------- AFAIK, win32ui is part of pywin32 ------------------------- Pythonwin.exe on about: pythonwin32 build 205 ------------------------- OS: Windows 2000 SP4 Dualcore: NO From vbgunz at gmail.com Sun Mar 5 07:40:22 2006 From: vbgunz at gmail.com (vbgunz) Date: 5 Mar 2006 04:40:22 -0800 Subject: Argument Precedence (possible bug?) Message-ID: <1141562422.491313.45110@i40g2000cwc.googlegroups.com> Hello all, I am just learning Python and have come across something I feel might be a bug. Please enlightenment me... The following code presents a challenge. How in the world do you provide an argument for *arg4? ## ============================================================ def argPrecedence(par1, par2=0, par3=0, *par4, **par5): print 'par1 =', par1, ' # positional argument' print 'par2 =', par2, ' # keyword argument' print 'par3 =', par3, ' # keyword argument' print 'par4 =', par4, ' # argument converted to tuple' print 'par5 =', par5, ' # argument converted to dictionary' argPrecedence('arg1', par3='arg3', par2='arg2', par5='arg5') # argPrecedence Results: par1 = arg1 # positional argument par2 = arg2 # keyword argument par3 = arg3 # keyword argument par4 = () # argument converted to tuple par5 = {'arg5': 'arg5'} # argument converted to dictionary ## ============================================================ The code above is verbose with comments because I am just learning Python and am creating my own examples and reference materials... Can you solve the problem? If so, can you share the solution? If not, is this a bug, limitation or is it a feature? Thank you for your time on this one! PS. I could be far off with this codes purpose; to try and create an example that will house all the different possible parameters (positional, keyword, * and **) in one single def statement. -- Best Regards Victor B. Gonzalez From apardon at forel.vub.ac.be Mon Mar 13 08:04:06 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Mar 2006 13:04:06 GMT Subject: Why python doesn't use syntax like function(, , x) for default parameters? References: <44115054$0$14937$834e42db@reader.greatnowhere.com> Message-ID: Op 2006-03-10, Terry Reedy schreef : > > "Antoon Pardon" wrote in message > news:slrne1372v.mt4.apardon at rcpc42.vub.ac.be... >> but nobody seems to have >> a problem with range(n) where n suddenly is the second parameter and >> we use the default for the first. > > Actually, I consider the unique calling pattern for x/range to be something > of a wart. Learning this inconsistency was at least a minor problem. It > is a rather extreme example of typing laziness beats purity. > > Given that enumerate() eliminate many uses of range(), it might be worth > considering requiring the start param. range(0,n) only takes two more > keystrokes. Better maybe to shorten range to rng to get them back ;-) Take the split method of strings. Personnaly I would prefer to be able to write: s.split(,3) Instead of having to write s.split(None,3) The reason is that None is IMO an implemenation detail here. Also the alternative s,split(maxsplit=3) doesn't work in this case. What may be an option for the future is a Default Object. So that if you have. def f(x=0,y=0): ... then f(Default, 5) would be equivallent to f(0,5) -- Antoon Pardon From http Mon Mar 20 08:00:08 2006 From: http (Paul Rubin) Date: 20 Mar 2006 05:00:08 -0800 Subject: cmp() on integers - is there guarantee of returning only +-1 or 0? References: <441dd94c$0$20108$834e42db@reader.greatnowhere.com> <1hcgdwr.zg61xysokadwN%aleaxit@yahoo.com> Message-ID: <7x4q1tfezr.fsf@ruckus.brouhaha.com> Christoph Zwerschke writes: > def sign(x): return (x>0)-(x<0) Cute, I'll try to remember that one. From hove at ntnu.no Tue Mar 21 03:50:21 2006 From: hove at ntnu.no (Joakim Hove) Date: Tue, 21 Mar 2006 09:50:21 +0100 Subject: Become another user Message-ID: Hello, [Disclaimer: This might really be a Unix question ?!] I have written a cgi-script in python - it works reasonably well. The script is invoked by the apache web server and runs as user 'wwwrun'. During the execution of the script I want to save some files, as the script is run bu user 'wwwrun' that is also the resulting ownership of the files created. Since I don't have root access on the server these files create some hassle. Hence my question is whether it is possible (from the the python script) to change identity 'wwwrun' -> 'myuser' during execution? Best Regards Joakim Hove -- Joakim Hove hove AT ntnu.no / Tlf: +47 (55 5)8 27 13 / Stabburveien 18 Fax: +47 (55 5)8 94 40 / N-5231 Paradis http://www.ift.uib.no/~hove/ / 55 91 28 18 / 92 68 57 04 From johnjsal at NOSPAMgmail.com Mon Mar 20 12:53:16 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 20 Mar 2006 17:53:16 GMT Subject: New-style Python icons In-Reply-To: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> Message-ID: and-google at doxdesk.com wrote: > Personally, I *like* the new website look, and I'm glad to see Python > having a proper logo at last! > > I've taken the opportunity to knock up some icons using it, finally > banishing the poor old standard-VGA-palette snake from my desktop. If > you like, you can grab them from: > > http://www.doxdesk.com/img/software/py/icons.zip > > in .ICO format for Windows - containing all resolutions/depths up to > and including Windows Vista's crazy new enormo-icons. Also contains the > vector graphics source file in Xara format. You can also see a preview > here: > > http://www.doxdesk.com/img/software/py/icons.png > Very nice, thanks! From brian at sweetapp.com Tue Mar 28 05:54:28 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 28 Mar 2006 12:54:28 +0200 Subject: New Python logo in high resolution format In-Reply-To: <1143253157.4203.20.camel@localhost.localdomain> References: <1143128619.670174.282160@t31g2000cwb.googlegroups.com> <1143226189.547274.90720@t31g2000cwb.googlegroups.com> <1143253157.4203.20.camel@localhost.localdomain> Message-ID: <442915E4.9030009@sweetapp.com> The new Python logo is available in high-resolution format here: http://tinyurl.com/n4rge Cheers, Brian From exhuma at gmail.com Mon Mar 20 09:40:22 2006 From: exhuma at gmail.com (exhuma.twn) Date: 20 Mar 2006 06:40:22 -0800 Subject: mod_python + publisher + psp + session problems In-Reply-To: <1142850573.405091.273060@v46g2000cwv.googlegroups.com> References: <1142848387.744835.6120@e56g2000cwe.googlegroups.com> <1142850573.405091.273060@v46g2000cwv.googlegroups.com> Message-ID: <1142865622.916213.210530@g10g2000cwb.googlegroups.com> grahamd at dscpl.com.au wrote: > exhuma.twn wrote: > > Hi again, > > > > as soon as I try to make use of the "session" object inside a > > psp-template file, I get the following error: > > > > Mod_python error: "PythonHandler mod_python.publisher" > > > > Traceback (most recent call last): > > > > File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line > > 299, in HandlerDispatch > > result = object(req) > > > > File "/usr/lib/python2.4/site-packages/mod_python/publisher.py", line > > 143, in handler > > result = str(result) > > > > File "/usr/lib/python2.4/site-packages/mod_python/psp.py", line 228, > > in __str__ > > self.run() > > > > File "/usr/lib/python2.4/site-packages/mod_python/psp.py", line 191, > > in run > > session = Session.Session(req) > > > > File "/usr/lib/python2.4/site-packages/mod_python/Session.py", line > > 389, in Session > > timeout=timeout, lock=lock) > > > > File "/usr/lib/python2.4/site-packages/mod_python/Session.py", line > > 294, in __init__ > > timeout=timeout, lock=lock) > > > > File "/usr/lib/python2.4/site-packages/mod_python/Session.py", line > > 132, in __init__ > > Cookie.add_cookie(self._req, self.make_cookie()) > > > > File "/usr/lib/python2.4/site-packages/mod_python/Session.py", line > > 160, in make_cookie > > c.path = dirpath[len(docroot):] > > > > TypeError: unsubscriptable object > > > > Any ideas? > > Upgrade to mod_python 3.2.8 and your problem will go away. > > See: > > http://issues.apache.org/jira/browse/MODPYTHON-50 > > I suggest that in future you use the mod_python mailing list for > questions > as that is where most knowledgeable people on mod_python hang out. > > Graham Thanks a lot Graham. This solved the problem. From alainpoint at yahoo.fr Wed Mar 8 04:20:49 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 8 Mar 2006 01:20:49 -0800 Subject: class variables for subclasses tuple Message-ID: <1141809649.911658.90570@p10g2000cwp.googlegroups.com> Hello, I have got a problem that i can't readily solve. I want the following: I want to create a supertuple that behaves both as a tuple and as a class. It should do the following: Point=superTuple("x","y","z") # this is a class factory p=Point(4,7,9) assert p.x==p[0] assert p.y==p[1] assert p.z==p[2] I already found a recipe to do that (recipe 6.7 in the Python cookbook). I reproduce the code hereunder: def superTuple(*attribute_names): " create and return a subclass of `tuple', with named attributes " # make the subclass with appropriate _ _new_ _ and _ _repr_ _ specials typename='Supertuple' nargs = len(attribute_names) class supertup(tuple): _ _slots_ _ = ( ) # save memory, we don't need per-instance dict def _ _new_ _(cls, *args): if len(args) != nargs: raise TypeError, '%s takes exactly %d arguments (%d given)' % ( typename, nargs, len(args)) return tuple._ _new_ _(cls, args) def _ _repr_ _(self): return '%s(%s)' % (typename, ', '.join(map(repr, self))) # add a few key touches to our new subclass of `tuple' for index, attr_name in enumerate(attribute_names): setattr(supertup, attr_name, property(itemgetter(index))) supertup._ _name_ _ = typename return supertup Now my problem is: i would like to extend this supertuple with class variables so that i can obtain the following: assert Point.x==0 assert Point.y==1 assert Point.z==2 while still having: assert p.x==p[0] assert p.y==p[1] assert p.z==p[2] This is not the case unfortunately: Point.x=0 leads to having p.x==0 It seems not possible to have class variables and instance variable having the same name and yet different values. Alain From r.pellegrini at gmail.com Thu Mar 16 09:46:53 2006 From: r.pellegrini at gmail.com (Rocco) Date: 16 Mar 2006 06:46:53 -0800 Subject: looking for atomixlib In-Reply-To: <1142235529.289850.17050@u72g2000cwu.googlegroups.com> References: <1142235529.289850.17050@u72g2000cwu.googlegroups.com> Message-ID: <1142520412.895394.153360@v46g2000cwv.googlegroups.com> here you'll find it in svn. http://trac.defuze.org/browser/oss From __peter__ at web.de Fri Mar 10 12:20:41 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 10 Mar 2006 18:20:41 +0100 Subject: operator creation? References: Message-ID: Gerardo Herzig wrote: > Lets say i have an DB object, who implements the querys to the database > trough a method called DBObject.doQuery. > > On the other hand, i have 50 sql functions stored in the database. So i > can call DBObject.doQuery('select * from my_sql_function()')...Ok, what > do i want to achieve, is some mecanism to be able to call > > DBObject.my_sql_function(), but without actually having to declare the > method called "my_sql_function". May be with creating a `->' operator... > maybe overrwriting the '.' operator... That's what __getattr__() is for. It is called when an attribute of the DBObject instance doesn't exist. The function 'method' defined inside __getattr__() remembers what the variable sql is bound to on that particular call ("closure"). Because we update the class with 'method', instead of __getattr__() subsequent calls will not my_sql_function() directly. class DBObject(object): def doQuery(self, sql): print "executing", sql def __getattr__(self, name): sql = "SELECT * FROM %s();" % name def method(self): return self.doQuery(sql) # insert the new method into the class # so that it has to be created only once setattr(self.__class__, name, method) return getattr(self, name) # infinite recursion # prevented by prior setattr() dbo = DBObject() dbo.my_sql_function() dbo.my_other_sql_function() Peter From duncan.booth at invalid.invalid Wed Mar 15 11:39:33 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 Mar 2006 16:39:33 GMT Subject: newbie questions References: <1142436837.547047.308520@j52g2000cwj.googlegroups.com> Message-ID: meeper34 wrote: > 4. Really basic question, and I'm sure I will learn this very quickly > with more reading, but I'm confused by the lack of an entry point in a > Python app, i.e. int main(). Keir's answer about testing for __main__ is good, but it might also help you to think a bit about what it actually means to run a Python program. Python executes code line by line from top to bottom. Almost every statement in Python is executed. This is quite different from a language like C where executable statements are safely tucked inside functions and execution starts at an arbitrary point (the 'main' function), or even C++ where global and static variable initialisations are also executable. In Python everything except the 'global' statement is executed at runtime (also comments and docstrings don't execute). That includes 'import', 'class' and 'def'. So, when you run a Python script it starts on the first line of the script. Usually that will be an 'import', so the interpreter will go off and find the referenced module, compile it if required, and then execute the module from top to bottom. If a module is imported more than once, it only starts executing the code in that module on the first import, and if you have circular imports you can end up accessing a module which has only partly executed. When it sees a class definition the interpreter executes its body in a new namespace and uses the result to create the class. When it sees a function definition it doesn't execute the body, but it does execute any default arguments and then it creates the function. What does this mean in practice? You cannot reference a class or function until after you have executed the relevant definition. You can stick a function definition inside a loop if you want: the name just gets rebound to a new object each time it is executed. The behaviour can be quite suprising at times for people who think of declaring functions, but it is extremely logical if you remember that everything has to execute. The __name__=='__main__' convention works because the main script executes in the module called '__main__', whereas every other module executes under its own name. But it isn't really the start of the program: rather it is the very last thing executed after all the modules have imported and done whatever initialisation they want, and after all the classes and functions have been defined. From hancock at anansispaceworks.com Wed Mar 1 19:17:51 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 1 Mar 2006 18:17:51 -0600 Subject: PEP 354: Enumerations in Python In-Reply-To: <87mzgb2be1.fsf@rose.polar.local> References: <87accdplbj.fsf@rose.polar.local> <87mzgb2be1.fsf@rose.polar.local> Message-ID: <20060301181751.164846ce@samwise.anansi> On Wed, 01 Mar 2006 12:37:26 +1100 Ben Finney wrote: > Ben Finney writes: > > PEP: 354 > > Title: Enumerations in Python > > Version: $Revision: 42186 $ > > Last-Modified: $Date: 2006-01-26 11:55:20 +1100 (Thu, > > 26 Jan 2006) $ > > Most people seem to be unopposed or in favour of some kind > of enumeration mechanism making it at least as far as the > standard library. ... but not to built-ins. That seems about right to me. > As I understand it, the current outstanding debates are:: > > * Builtin types versus stdlib module (maybe > 'collections') > > * Ordered sequences versus unordered iterables > > * Immutable versus mutable I suggest that both are called for, but would have different names -- the Immutable is the actual "Enum", the mutable is probably a "Vocabulary" or something else. > * Bad comparisons: raise exception versus return > NotImplemented It should raise an error, because client code should use enumerated values if enumerated values are spec'd in the API. > * Terminology for each of these concepts + Tracing of individual "EnumValues" (or "symbols"?) to their enum, I should be able to interrogate a value to find what enum it comes from in addition to being able to interrogate an enum to find out what values belong to it. Which is more computationally efficient will depend on the application, and a single application might do better to use each for different tasks, so I think it should be reversible. + How about documentation of enumerated values? (Where does the enum's __doc__ go?). One of the main values of using enumerated values is as an aid to documentation, but "WED" is still vague. Could be "Wednesday", could be the "Western Education District" or short for "Wedding". Enumerations are most frequently used in module APIs, so they are important to document. Obviously, the point is so that documentation tools like epydoc can capture the enumeration documentation. -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From sybrenUSE at YOURthirdtower.com.imagination Sat Mar 11 10:35:37 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sat, 11 Mar 2006 16:35:37 +0100 Subject: why use special config formats? References: <1142002082.976945.261900@e56g2000cwe.googlegroups.com> <1142084978.324380.95780@v46g2000cwv.googlegroups.com> Message-ID: gangesmaster enlightened us with: > YES THATS THE POINT. PYTHON CAN BE USED JUST LIKE A CONFIG FILE. AND CAN ALSO BE MISUSED AND HARDER TO USE THAN A SIMPLE CONFIG FILE. Get it into your thick head that you're plain wrong 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 http Wed Mar 8 16:55:25 2006 From: http (Paul Rubin) Date: 08 Mar 2006 13:55:25 -0800 Subject: cgi problem References: <7xk6b5mjpw.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xmzg0ob3m.fsf@ruckus.brouhaha.com> Thomas Guettler writes: > > back to the originating url, i.e. I want the cgi to send a 302 redirect. > > I have this setup for a small script (for bigger things I use quixote)... Thanks. It looks like you've written your cgi completely from scratch. I was hoping to use the cgi module, which has some convenient features for reading the query parameters and POST content. I should look into Quixote and some of the other Python web frameworks but this particular task is pretty simple so I thought I'd just use a cgi. From johnjsal at NOSPAMgmail.com Fri Mar 17 15:02:31 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 17 Mar 2006 20:02:31 GMT Subject: style guideline for naming variables? In-Reply-To: References: Message-ID: John Salerno wrote: > some_function > > But this seems awkward to me. someFunction seems nicer Sorry, I was asking about variables but used a function example. But really I'm asking about any situation where you might want to use multiple words (except for classes, which is recommended to use Camel case, and that seems fine). From apardon at forel.vub.ac.be Fri Mar 10 10:33:52 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Mar 2006 15:33:52 GMT Subject: Why python doesn't use syntax like function(, , x) for default parameters? References: <44115054$0$14937$834e42db@reader.greatnowhere.com> Message-ID: Op 2006-03-10, Roy Smith schreef : > In article , > Antoon Pardon wrote: > >> Op 2006-03-10, Roy Smith schreef : >> > "Dmitry Anikin" wrote: >> >> There are often situations when a function has independent >> >> parameters, all having reasonable defaults, and I want to >> >> provide just several of them. In fact, I can do it using >> >> keyword parameters, but it's rather long and you have to >> >> remember/lookup names of parameters. >> > >> > Specifying the names of the keyword parameters costs you a little typing >> > once, but saves everybody (including yourself) a lot of grief later when >> > you're trying to figure out what the heck your code does 6 months later. >> >> Could you explain what is so hard in figuring out: >> >> func(,,4) > > Because while I probably remember what func does (especially if it's well > named), it's less likely that I remember all the arguments it takes, and > even less that I remember what order they come in. Do you have trouble remembering that range(n) is actually providing the second parameter to the function and what it does? > Let's say I've got a function which makes a network connection. It takes > optional arguments for a port number to connect to, a timeout (in seconds) > and a buffer size (in kbytes) to use. If we used your syntax, what does > "connect (,,20)" mean? You have to go look up the definition of the > function to find out, don't you? But, if I wrote "connect (port=20)", it's > obvious to anybody reading the code what the 20 is. I don't consider this an argument. We already have the problem that we need to figure out what connect(20) means. connect(,,20) will at least make it clear that some parameters are missing. My syntax doesn't make it easier to introduce inclarities than python can. Sure connect(port=20) provides extra clarity, but nobody seems to have a problem with range(n) where n suddenly is the second parameter and we use the default for the first. If we want to allow things like that I would prefer range(,n) that at least makes it clear what is going on. -- Antoon Pardon From greg at cosc.canterbury.ac.nz Wed Mar 1 04:28:36 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 01 Mar 2006 22:28:36 +1300 Subject: PEP 354: Enumerations in Python In-Reply-To: References: <87accdplbj.fsf@rose.polar.local> <4402B91A.4010108@tim.thechases.com> Message-ID: <46l8jtFbnfgeU5@individual.net> Dan Sommers wrote: > In some parts of the world, calendar weeks begin on Monday > and end on Sunday, and in other parts of the world, work weeks begin on > Sunday and end on Thursday. Things like days of the week really have a circular ordering, so it doesn't inherently make sense to ask whether one day of the week is less than or greater than another. Maybe there should be a circular_enum type, where order comparisons even among the *same* type are disallowed? Another thought -- should enum values have pred() and succ() methods, like in Pascal? If so, for a circular_enum these should wrap around. -- Greg From scott.daniels at acm.org Sun Mar 19 10:14:42 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 19 Mar 2006 07:14:42 -0800 Subject: ANNOUNCE: xlrd 0.5.2 -- extract data from Excel spreadsheets In-Reply-To: <441d4120$1_1@newspeer2.tds.net> References: <441c7714$1_2@newspeer2.tds.net> <441C9F4D.1030203@lexicon.net> <441ccb61$1_3@newspeer2.tds.net> <441D23F2.7090808@lexicon.net> <441d4120$1_1@newspeer2.tds.net> Message-ID: <441d7318$1@nntp0.pdx.net> Kent Johnson wrote: > John Machin wrote: >> * Herewith the biased comparison: .... > > Thank you! Thank you (John) as well. I realize you are a bit reluctant to toot your own horn, but it is just this kind of biased comparison that let's us know whether to investigate further. It also helps that you mention what pyExcelerator is good at. -- -Scott David Daniels scott.daniels at acm.org From kp8 at mac.com Sat Mar 18 05:27:47 2006 From: kp8 at mac.com (kpp9c) Date: 18 Mar 2006 02:27:47 -0800 Subject: Is there no end to Python? In-Reply-To: <1142627765.683262.27120@i39g2000cwa.googlegroups.com> References: <1142622194.560240.4330@j52g2000cwj.googlegroups.com> <1142627765.683262.27120@i39g2000cwa.googlegroups.com> Message-ID: <1142677667.002061.269760@p10g2000cwp.googlegroups.com> >> This is good thing because I can ignore what I don't need. I am finding that this is really not true for me. I find that if i use other folks code, collaborate, or get help from other folks i still have to know all the new constructs that i don't often use, and i really struggle with iterators and generators and some of the newer things and folks seem to have fallen in love with ridiculously complex list comprehensions. (i'll admit i love the list comprehensions too, but too a point) Don't get me wrong, i LOVE Python, but since 2.2 or so the language has started to get some feature creep and is starting to evolve exponentially fast and while all that pre 2.2 code is really readable still, i see some stuff now that really really hurts my brain. We see less silly lambdas than we used to, and Python is more powerful than ever, but i think there has been a cost too. Python has become harder to read and *MUCH* harder to learn all of a sudden. Personally i would like to see the core Python language evolve more slowly and see work on packages, modules and DOCS!! but i am sure that is very much a minority opinion. I found the language additions of 2.3 and 2.4 really hard to absorb. flame away... -kp-- From godoy at ieee.org Thu Mar 30 12:45:32 2006 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 30 Mar 2006 14:45:32 -0300 Subject: Very stupid question. References: <1143739683.410001.118730@t31g2000cwb.googlegroups.com> Message-ID: <87psk3ddxf.fsf@ieee.org> "Sullivan WxPyQtKinter" writes: > How to get the length of a file via build-in file object support? In > Visual Basic there is len(file) of something like that. But in python, > where is this property? > > Sorry for this stupid question, if it is. pydoc os and then look for "stat"... In "stat_result" there's a description of the tuple you'll get. -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From felipe.lessa at gmail.com Tue Mar 14 18:47:14 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 14 Mar 2006 20:47:14 -0300 Subject: Python Debugger / IDE ?? In-Reply-To: <1142358243.640532.278480@z34g2000cwc.googlegroups.com> References: <1142357338.313046.139060@i39g2000cwa.googlegroups.com> <1142358243.640532.278480@z34g2000cwc.googlegroups.com> Message-ID: <1142380034.5371.0.camel@kenshin> Em Ter, 2006-03-14 ?s 09:44 -0800, danmcleran at yahoo.com escreveu: > >Is there any editor or IDE in Python (either Windows or Linux) which > >has very good debugging facilites like MS VisualStudio has or something > >like that. > > I've been using Eclipse with PyDev and am very happy with it. I second that. It's the best Python IDE I've ever used. But you won't get too far with less than 512 MiB of RAM... -- "Quem excele em empregar a for?a militar subjulga os ex?rcitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destr?i os estados dos outros povos sem lutas prolongadas. Deve lutar sob o C?u com o prop?sito primordial da 'preserva??o'. Desse modo suas armas n?o se embotar?o, e os ganhos poder?o ser preservados. Essa ? a estrat?gia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" From jstroud at ucla.edu Sat Mar 4 16:19:29 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 04 Mar 2006 13:19:29 -0800 Subject: How to except the unexpected? In-Reply-To: References: Message-ID: Rene Pijlman wrote: > Steven D'Aprano: > >>ExpectedErrors = (URLError, IOError) >>ErrorsThatCantHappen = >> >>try: >> process_things() >>except ExpectedErrors: >> recover_from_error_gracefully() >>except ErrorsThatCantHappen: >> print "Congratulations! You have found a program bug!" >> print "For a $327.68 reward, please send the following " \ >> "traceback to Professor Donald Knuth." >> raise >>except: >> print "An unexpected error occurred." >> print "This probably means the Internet is broken." >> print "If the bug still occurs after fixing the Internet, " \ >> "it may be a program bug." >> log_error() >> sys.exit() > > > Yes, I think I'll do something like this. Perhaps combined with Peter's > advice to not micromanage, like so: > > Reraise = (LookupError, ArithmeticError, AssertionError) # And then some > > try: > process_things() > except Reraise: > raise > except: > log_error() > Why catch an error only to re-raise it? This falls under http://c2.com/cgi/wiki?YouReallyArentGonnaNeedThis From brenner at informatik.uni-freiburg.de Fri Mar 10 09:06:03 2006 From: brenner at informatik.uni-freiburg.de (Michael Brenner) Date: Fri, 10 Mar 2006 15:06:03 +0100 Subject: import and shared global variables Message-ID: <441187CB.6000806@informatik.uni-freiburg.de> Hi, I'm implementing a plugin-based program, structured like the example below (where m1 in the main module, loading m2 as a plugin). I wanted to use a single global variable (m1.glob in the example) to store some config data that the plugins can access. However, the output shown belown seems to imply that glob is *copied* or recreated during the import in m2. Am I missing something? I thought m1 should be in sys.modules and not be recreated during the import in m2. After browsing c.l.p, it seems that this is probably somehow due to the circular import. However, I do not really see why this should be a problem here. Interestingly, the problem disappears when I put the code in m1 in a real main() function instead of "if __name__" etc. Though this seems to solve my problem, I still want to understand what's happening. Thanks, michael m1.py: ------ glob = [1] if __name__ == "__main__": glob.append(2) print "m1.main().1:", glob m2 = __import__("m2") m2.test() print "m1.main().2:", glob ------ m2.py: ------ def test(): import m1 print "m2.test():", m1.glob ----- Output: m1.main().1: [1, 2] m2.test(): [1] m1.main().2: [1, 2] From rrr at ronadam.com Wed Mar 15 16:12:26 2006 From: rrr at ronadam.com (Ron Adam) Date: Wed, 15 Mar 2006 15:12:26 -0600 Subject: pretty print, tidy, reindent.py In-Reply-To: <1142453697.237020.180010@i39g2000cwa.googlegroups.com> References: <1142453697.237020.180010@i39g2000cwa.googlegroups.com> Message-ID: kpp9c wrote: > What ever happened to reindent.py ? This used to be part of the > distribution. Does it still work with modern versions of python? > > A lot of the code i drag off here (even if i use "show original"!) > comes out all messed up and i end up having to clean a lot of it up. I > wonder if there is a reformatter/pretty printer that like perl tidy > that might help. I see i have tabnanny, but that only complains... i > want something that fixes automagically. > > -kp8-- What you're looking for is in "Python24/Tools/Scripts" directory. Cheers, Ron From bobrien18 at yahoo.com Mon Mar 6 14:56:50 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 6 Mar 2006 11:56:50 -0800 Subject: Need help initializing a list or tuple. In-Reply-To: References: <1141664498.539402.43160@e56g2000cwe.googlegroups.com> Message-ID: <1141675010.414126.321400@j33g2000cwa.googlegroups.com> nope.. sorry its not... I meant x = [[1,2,3],[3,4,5],[5,6,7]] From larry.bates at websafe.com Thu Mar 30 09:20:53 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 30 Mar 2006 08:20:53 -0600 Subject: How to determine an object is "scriptable" In-Reply-To: <1143726903.153135.317880@j33g2000cwa.googlegroups.com> References: <1143726903.153135.317880@j33g2000cwa.googlegroups.com> Message-ID: abcd wrote: > I recently came across a problem where I saw this error: > "TypeError: unsubscriptable object" > > How can I determine if an object is "scriptable" or "unscriptable"? > Simplest answer is to use isinstance to see if it is a string, list, or tuple: if isinstance(variable, (str, list, tuple)): . . . Now the problem is that this answer doesn't address the problem. Your code is attempting to do something to the wrong type of object/variable which is a logic problem. -Larry Bates From brucedecoy-post at yahoo.com.au Mon Mar 20 08:02:14 2006 From: brucedecoy-post at yahoo.com.au (Bruce Cropley) Date: 20 Mar 2006 05:02:14 -0800 Subject: Is there such an idiom? In-Reply-To: <1142813592.486643.111550@j33g2000cwa.googlegroups.com> References: <1142813592.486643.111550@j33g2000cwa.googlegroups.com> Message-ID: <1142859734.204209.90280@e56g2000cwe.googlegroups.com> Per wrote: > http://jaynes.colorado.edu/PythonIdioms.html [snip] > Is this correct? > s = [1,2,3,4,5...] > t = [4,5,6,,8,...] > how to find whether there is/are common item(s) between two list in > linear-time? > how to find the number of common items between two list in linear-time? A common technique if both lists are sorted is to iterate through both lists in parallel, advancing the smaller iterator each time. This is the merge algorithm that is used by a merge sort, and it is O(s+t). For two lists, the algorithm would go something like: while not finished: if s_iter_val < t_iter_val: move s_iter on elif s_iter_val > t_iter_val: move t_iter on else: include / yield the value move both iters on For more on the standard merge algorithm, see: http://en.wikipedia.org/wiki/Merge_algorithm For an intersection merge, I hacked the recursive solution from there... def merge(a, b): if len(a) == 0: return [] if len(b) == 0: return [] if a[0] < b[0]: return merge(a[1:], b) elif a[0] > b[0]: return merge(a, b[1:]) else: return a[0:1] + merge(a[1:], b[1:]) #-------------------------8<------------------------- import unittest class TestMerge(unittest.TestCase): def test_merge(self): self.assertEquals(merge([1,2],[]), []) self.assertEquals(merge([],[1,2]), []) self.assertEquals(merge([1,3,5],[2,4,6]), []) self.assertEquals(merge([1,2,3],[3,4,5]), [3]) self.assertEquals(merge([1,2,3,5,6,7],[3,4,5,7,8]), [3,5,7]) if __name__ == "__main__": unittest.main() HTH, Bruce From vinay_sajip at yahoo.co.uk Fri Mar 10 13:36:14 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 10 Mar 2006 10:36:14 -0800 Subject: python 2.4 logging module References: <1142008625.060464.137980@z34g2000cwc.googlegroups.com> Message-ID: <1142015774.067816.268060@j52g2000cwj.googlegroups.com> Pramod wrote: > Hi All, > > How can I remove an Instance of logger ? > I need this feature in one of my script where I need to associate each > time logger instance to different handler. > > Thanks in advance > Pramod Are you sure you are using logging in the right way? What do you mean by "each time"? You can use addHandler and removeHandler, but the Logger instance stays - it's effectively a singleton. Vinay Sajip From fredrik at pythonware.com Tue Mar 21 15:14:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 21 Mar 2006 21:14:25 +0100 Subject: Why "class exceptions" are not deprecated? References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com> <1142971205.781917.160380@z34g2000cwc.googlegroups.com> Message-ID: Gregory Petrosyan wrote: > Thanks for answer. But what about "Explicit is better than implicit"? "Practicality beats purity" Changing the language just because some random guy on a newsgroup read the tutorial backwards isn't really practical. From http Fri Mar 10 01:13:11 2006 From: http (Paul Rubin) Date: 09 Mar 2006 22:13:11 -0800 Subject: counting number of (overlapping) occurances References: <1141968108.977332.261010@i40g2000cwc.googlegroups.com> <7x3bhq7tf0.fsf@ruckus.brouhaha.com> <1141970477.071343.160300@j52g2000cwj.googlegroups.com> Message-ID: <7xy7zi6d54.fsf@ruckus.brouhaha.com> "John" writes: > This works but is a bit slow, I guess I'll have to live with it. > Any chance this could be sped up in python? Whoops, I meant to say: len([1 for i in xrange(len(s1)) if s1.startswith(s2,i)]) That avoids creating a lot of small strings. If s1 is large you may want to use fancy algorithms like Boyer-Moore string search. If s2 is also large, you could have some kind of finite state machine scan through s1 so it recognizes overlapping occurrences of s2 in parallel. There might be some way to combine that with Boyer-Moore. From fredrik at pythonware.com Thu Mar 16 15:20:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Mar 2006 21:20:08 +0100 Subject: Counting nested loop iterations References: <1142539976.631204.108260@u72g2000cwu.googlegroups.com> Message-ID: Derek Basch wrote: > What is the best way to count nested loop iterations? I can only figure > to use an index but that seems kludgy. > > index = 0 > for animal in zoo: > for color in animal: > index += 1 what's kludgy with using a counter to count things ? (the real question here is of course why you need the counter. what's the loop doing? if the code you posted is all you have, you can replace it with index = sum(len(animal) for animal in zoo), but I assume you want to do more stuff in there...) From deets at nospam.web.de Tue Mar 21 16:32:40 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 21 Mar 2006 22:32:40 +0100 Subject: Can XML-RPC performance be improved? In-Reply-To: References: <48apnrFj7ambU1@uni-berlin.de> Message-ID: <48b9noFj8e8jU1@uni-berlin.de> > Beware, CORBA marshaling/unmarshaling can be similarly deadly, especially if > you are passing Any's and have to marshal complex type codes. But if you > are just sending arrays of octets, or strings of chars, then CORBA > marshal/unmarshal will be quite fast. Sure, any is no good at all. But I guess having a well-defined struct makes send corba the data comparably packed and (give or take endianess) directly in a representation close to what the result will look like. In contrast to XML, that wraps _everything_ in a plethora of bytes just for the fun of it... > Of course, something will have to convert that array to meaningful data > *somewhere*! You can't really eliminate software complexity, you can only > move it around. (not original, I'm quoting Chris Stone, founder of the OMG. > Also from Chris Stone - "I finally came up with a good definition for > middleware. Middleware is the software nobody wants to pay for.") Also true - but you can make the matter of reinterpreting a bunch of bytes a mere cast (TCP/IP solution) or invoke a few thousand lines of code called XML-Parser. And on top of _that_ the XMLRPC itself. CORBA is certainly between these two, but on a scale of 5-20 times faster. Which might be the difference between a loaded but responsive server and a self-inflicted DDOS :) Diez From no-spam at no-spam-no-spam.com Wed Mar 15 10:04:12 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Wed, 15 Mar 2006 16:04:12 +0100 Subject: global, globals(), _global ? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > "robert" wrote: > > >>Most variable read-s in Python anyway go to module globals - as there >>are no other kinds of namespaces except __builtins__ > > > your post made some sense until I got to this paragraph, which appears to > completely ignore local variables, arguments, and variables in intermediate > scopes ? maybe you could clarify ? Of course the local namespaces on the stack are the unmentioned default (the intermediate frames are half way on the stack ..). The discussion focused on off-stack, "common" name spaces. Python has done the right magic in order to let modularize code well. Just self-similiar self-inspection is not (yet) done to the best in some places: this "_global" own module, self inspection in functions/classes/methods (nameless recursion), stack handling/callcc Robert From recombinant at hotmail.com Thu Mar 9 17:25:07 2006 From: recombinant at hotmail.com (Stephen D Evans) Date: Thu, 9 Mar 2006 22:25:07 -0000 Subject: Any python HTML generator libs? References: <1141936438.584242.129220@z34g2000cwc.googlegroups.com> Message-ID: Jarek Zgoda wrote: > I use HTMLTemplate + ElementTree combo to generate static HTML documents > from data in XML files. Other way might be using "object oriented XSL", > as ll-xist is often advertized. HTMLTemplate + ElementTree works for me too. Additionally I use CSS (Cascading Style Sheets) to add style (e.g. fonts, colors and spacing). The CSS also allows for different styles for display/print (e.g. not printing menus). If you want to see artistic CSS google for "css Zen Garden" . Nearly two years after initially using HTMLTemplate, the python code, templates and css are easy to maintain. Whereas some code/markup written with a python HTML generator is difficult to maintain. Stephen D Evans From elad.gerson at gmail.com Sun Mar 19 08:30:10 2006 From: elad.gerson at gmail.com (Elad) Date: 19 Mar 2006 05:30:10 -0800 Subject: Problems redirecting STDOUT (NOT sys.stdout) to a pipe. Message-ID: <1142775009.997651.189160@i40g2000cwc.googlegroups.com> Hello All, I am trying to capture some printf's from a C function called by python. I have tried to following: STDOUT = 1 # stdout fd (re, we) = os.pipe() # Create re / write handlers dup2(we, STDOUT) # override system's stdout, should dup first and restore later.. call_my_hello_world() # if stdout is not overriden will print hello world on console screen x = os.read(re, 11) sadly, x = '' after the code is executed. help ? :-) Thanks, Elad. From sybrenUSE at YOURthirdtower.com.imagination Wed Mar 22 16:48:25 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 22 Mar 2006 22:48:25 +0100 Subject: Need help with restricting number of new objects a user script can create References: <1143047823.130502.267140@t31g2000cwb.googlegroups.com> <1143055192.370362.138800@j33g2000cwa.googlegroups.com> Message-ID: vj enlightened us with: > Run using lua generates: > > Fatal error: Allowed memory size of 8388608 bytes exhausted (tried > to allocate 35 bytes) in > /home/groups/d/do/doris/htdocs/lua/weblua.php on line 109 Ehm... this can also be done with Python & ulimit. 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 bj_666 at gmx.net Wed Mar 15 17:00:05 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 15 Mar 2006 23:00:05 +0100 Subject: mydate.strftime('%x') and cgi script References: <47lbrdFg58hmU1@news.dfncis.de> Message-ID: In <47lbrdFg58hmU1 at news.dfncis.de>, Sibylle Koczian wrote: > I'm writing a cgi script which only needs to run in a small LAN. I tried > to show dates in a reasonable format by using > > import locale > import datetime > > locale.setlocale(locale.LC_ALL, '') > ... > dt = datetime.date.today() > print dt.strftime('%x') > > This works well in other scripts or at the interactive prompt. It > doesn't work in a cgi script: in the browser the date is shown as > 'mm/dd/yyyy' which is _not_ my 'Locale's appropriate date > representation' as the documentation for strftime calls it. That's the web server's locale appropriate date representation then. Ciao, Marc 'BlackJack' Rintsch From lycka at carmen.se Thu Mar 30 07:08:07 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 30 Mar 2006 14:08:07 +0200 Subject: Looking for a language/framework In-Reply-To: References: <1143559444.045808.38790@u72g2000cwu.googlegroups.com> <1143573777.704126.281830@t31g2000cwb.googlegroups.com> Message-ID: Steve Juranich wrote: > akameswaran at gmail.com wrote: > >> As far as hosting, I also know >> where Zope/Plone hosting from 7.95 a month - although the host doesn't >> list it on their ads, they do use and host it. > > Which host would this be? I'm currently exploring some options for getting > a Zope site hosted. Virtual servers is getting cheaper and cheaper. That's obviously a viable way to host Zope, if you don't mind being your own sysop. From eight02645999 at yahoo.com Mon Mar 6 07:51:11 2006 From: eight02645999 at yahoo.com (eight02645999 at yahoo.com) Date: 6 Mar 2006 04:51:11 -0800 Subject: a good algo to do this Message-ID: <1141649471.773627.257960@i40g2000cwc.googlegroups.com> hi i need to do something like this eg given a number (as a string) = "123" there are a few combination i want to find with this string, ie "132","321","231","312" and "213". so there are 6 combinations altogether. i remember there's a formula for this, but forgot. Does python have any modules/functions to do this? thanks From hfuecks at gmail.com Sat Mar 11 13:19:00 2006 From: hfuecks at gmail.com (Harry Fuecks) Date: Sat, 11 Mar 2006 19:19:00 +0100 Subject: Python source cross reference doc generator? Message-ID: Hi All, Wondering if a tool exists to generate "cross reference" documentation for Python code bases? Particularly after something like phpxref - http://phpxref.sourceforge.net/ : written in Perl, scans a bunch of PHP scripts and generates HTML output that allows you to see all the classes / methods / functions / variables defined and (what I'm interested in) where they are referenced. Essentially something like API docs but with the addition of being able to see who's using a particular method Is there anything like this for Python? Have done much looking without success. Many thanks. From rocky at panix.com Fri Mar 31 11:08:48 2006 From: rocky at panix.com (R. Bernstein) Date: 31 Mar 2006 11:08:48 -0500 Subject: How to debug python code? References: <1143782330.199836.221880@v46g2000cwv.googlegroups.com> <0glp22l2g3geu2hivntn6uel24m5lau7s8@4ax.com> Message-ID: Dennis Lee Bieber writes: > On 30 Mar 2006 21:18:50 -0800, sushant.sirsikar at gmail.com declaimed the > following in comp.lang.python: > > > hi, > > I am new to Python programming.I am not getting exactly pdb.Can > > anyone tell me effective way to debug python code? > > I think I toyed with pdb back around 1993... Never needed it... > > Of course, with so many different languages and debuggers in my > life, I've never found time to master any but the old VMS debugger > (which is nothing more than a very complex error handler ) That's one reason why in my bash and GNU make debugger (and in extending pdb), I've stuck to the gdb command set: the effort that is spent mastering gdb can be transfered in the GNU Make, Bash, *AND* Python debuggers. From mforbes at lnsDOTmit.edu Thu Mar 9 02:18:29 2006 From: mforbes at lnsDOTmit.edu (Michael McNeil Forbes) Date: 08 Mar 2006 23:18:29 -0800 Subject: Python advocacy in scientific computation References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> Message-ID: Robert Kern writes: > sturlamolden wrote: ... > > 5. Versioning control? For each program there is only one > > developer and a single or a handful users. ... > This is one thing that a lot of people seem to get wrong: version > control is not a burden on software development. It is a great > enabler of software development. It helps you get your work done > faster and easier even if you are a development team of one. You can > delete code (intentionally!) because it's not longer used in your > code, but you won't lose it. You can always look at your history and > get it again. You can make sweeping changes to your code, and if > that experiment fails, you can go back to what was working > before. Now you can do this by making copies of your code, but > that's annoying, clumsy, and more effort than it's worth. Version > control makes the process easier and lets you do more interesting > things. > > I would go so far as to say that version control enables the > application of the scientific method to software development. When > you are in lab, do you say to yourself, "Nah, I won't write anything > in my lab notebook. If the experiment works at the end of the day, > only that result matters"? ... A slightly off topic note: I find that version control (VC) has many advantages for scientific research (I am a physicist). 1) For software as Robert mentions I find it indispensable. 2) Keeping track of changes to papers (as long as they are plain text like LaTeX). This is especially useful for collaborations: using the diff tools one can immediately see any changes a coauthor may have made. (I even use branching: maintaining one branch for the journal submission which typically has space restrictions, and another for preprint archives which may contain more information.) 3) Using VC allows you to easily bring another computer up to date with your current work. If I go to a long workshop and use local computing resources, I simply checkout my current projects and I can work locally. When I am done, I check everything back in and when I get home, I can sync my local files. ------- Another aspect of python I really appreciate are the unit testing facilities. The doctest, unittest, and test modules make it easy to include thorough tests: crucial for making sure that you can trust the results of your programs. Organizing these tests in MATLAB and with other languages was such a pain that I would often be tempted to omit the unit tests and just run a few simulations, finding errors on the fly. Now I almost always write unit tests along with---or sometimes before---I write the code. Michael. From mensanator at aol.com Thu Mar 16 19:48:57 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 16 Mar 2006 16:48:57 -0800 Subject: My Generator Paradox! References: <1142554666.740989.303350@p10g2000cwp.googlegroups.com> Message-ID: <1142556537.122420.146500@j33g2000cwa.googlegroups.com> vbgunz wrote: > I am afraid that this is the first time in which I would probably need > something explained to me as if I were a little child. I am having a > hard time getting this through my thick skull. What in the world is > wrong with this!? > > ''' ########################################################### ''' > > def generatorFunction(sequence=['item1', 'item2', 'item3']): > for item in sequence: > yield item > > yieldedValue = generatorFunction() > > '''this seems to work perfectly.''' > print '-' * 32 > print yieldedValue # > print yieldedValue.next() # item1 > print yieldedValue.next() # item2 > print yieldedValue.next() # item3 > > '''this is where things don't make any sense!''' > print '-' * 32 > print generatorFunction() # > print generatorFunction().next() # item1 > print generatorFunction().next() # item1 > print generatorFunction().next() # item1 > > ''' ########################################################### ''' > > the first set of calls assigned to yieldedValue work but the second set > without assignment don't. I asked for help on this at #python (I love > those people in there!) and was told the following... > generatorFunction() is a call (obvious) when calling the second set, I > am resetting the iteration and this explains why I only and always get > item1. > > ok. *but* why in the world does the first set of calls work? > technically, isn't yieldedValue == generatorFunction() on a name basis? > I mean isn't the following technically the same? > > generatorFunction() > yieldedValue = generatorFunction() No. Look at this >>> a = generatorFunction() >>> b = generatorFunction() >>> a==b False Why aren'y they the same? Here's a clue: >>> generatorFunction() >>> generatorFunction() Note the addresses are different. Try this >>> b.next() 'item1' >>> b.next() 'item2' >>> generatorFunction().next() 'item1' Just like your example, the generator re-initailized and printed item1. But that's not the same generator as b >>> b.next() 'item3' > > aren't they both the same? To me they should be but obviously this > creates the point of this paradox. I don't understand what is happening > here... Can someone care to explain why the assignment works but not > the direct call? In a sense shouldn't the assignment yield the same > results as the direct call and vice versa? I am confused :( > > Thank you for any help on this! From ajones1 at gmail.com Thu Mar 2 18:07:13 2006 From: ajones1 at gmail.com (ajones) Date: 2 Mar 2006 15:07:13 -0800 Subject: do design patterns still apply with Python? References: <8SINf.1718$No6.40137@news.tufts.edu> <1141333305.284973.54620@z34g2000cwc.googlegroups.com> Message-ID: <1141340833.768460.193010@j33g2000cwa.googlegroups.com> John Salerno wrote: > Yeah, that's what I was wondering. I wonder if, after reading a DP book, > I might have to 'unlearn' some things when applying them to Python. I would say adjust instead of unlearn. This is probably true to a lesser or greater extent of any language for which your DP book was not written. > But I suppose I should just do it first and then try to implement them > myself. OOP is just so mind-bending for me that I've kind of put off > patterns right now until I get more comfortable with it. :) I would suggest getting a good grasp on OOP before you get into design patterns. When most people start with any new concept they tend to try and see everything in terms of their new toy, so sticking to one or two new concepts at a time will make things a little easier. Design patterns are kind of like sarcasm: hard to use well, not always appropriate, and disgustingly bad when applied to problems they are not meant to solve. You will do just fine without them until OOP is at least familiar to you, and by that time you should be a little better able to use them appropriately. From uymqlp502 at sneakemail.com Thu Mar 9 17:37:31 2006 From: uymqlp502 at sneakemail.com (Russ) Date: 9 Mar 2006 14:37:31 -0800 Subject: implementation of "complex" type In-Reply-To: <1141907864.393055.99870@v46g2000cwv.googlegroups.com> References: <1141895757.128437.159460@i39g2000cwa.googlegroups.com> <1141907864.393055.99870@v46g2000cwv.googlegroups.com> Message-ID: <1141943851.606198.191010@z34g2000cwc.googlegroups.com> Thanks for the links, especially for the pure Python implementation. That provides a good model for similar classes. I am just wondering why your implementation of complex numbers does not have "assignment operators" such as "__iadd", etc. By the way, I suppose my original post (where I wrote, "I'd like to make my class behave like the "complex" class.") could be construed to mean that I was implementing my own version of the complex class. But I only meant that I want it to "behave" like the built-in complex class with regard to referencing and copying (as my code example showed). My apologies for any misunderstanding that occurred. From just at xs4all.nl Thu Mar 9 12:27:19 2006 From: just at xs4all.nl (Just) Date: Thu, 09 Mar 2006 18:27:19 +0100 Subject: First script, please comment and advise References: <1141917596.011498.311500@p10g2000cwp.googlegroups.com> <1141920446.935210.260650@j52g2000cwj.googlegroups.com> Message-ID: In article <1141920446.935210.260650 at j52g2000cwj.googlegroups.com>, bearophileHUGS at lycos.com wrote: > Just: > > > Btw. I find the use of a nested function here completely bogus: you > > don't need the surrounding scope. > > I don't agree, nested functions are useful to better structure your > program: to really nest things that are logically nested, to have just > one thing when you have only one thing to do, and they help you to > avoid polluting the namespace (those were the main purposes of nested > functions in Pascal-like languages). Luckily this is Python, not Pascal :) 1. The fact that one function calls the other doesn't mean they're "logically nested". 2. The helper function is useful on its own, so it is a waste to hide it inside another. 3. The nested function makes the enclosing function harder to read. 4. I don't buy the namespace pollution argument, we have modules after all. 5. Overhead: every time a new function object is created, for no good reason. (But you save a global name lookup, yet that doesn't appear to weigh up against the function def. [*]) To me, nested functions (in Python) are *only* helpful when using closures. If you're not using the enclosing scope, you're just obfuscating things. Just [*] % python2.4 -m timeit -s "def helper(): pass" "def nonnesting():" \ " helper()" "nonnesting()" 1000000 loops, best of 3: 1.92 usec per loop % python2.4 -m timeit "def nesting():" " def helper(): pass" \ " helper()" "nesting()" 100000 loops, best of 3: 2.04 usec per loop From peter at engcorp.com Fri Mar 3 20:01:19 2006 From: peter at engcorp.com (Peter Hansen) Date: Fri, 03 Mar 2006 20:01:19 -0500 Subject: How to except the unexpected? In-Reply-To: References: Message-ID: Rene Pijlman wrote: > One of the things I dislike about Java is the need to declare exceptions > as part of an interface or class definition. But perhaps Java got this > right... > > I've writen an application that uses urllib2, urlparse, robotparser and > some other modules in the battery pack. One day my app failed with an > urllib2.HTTPError. So I catch that. But then I get a urllib2.URLError, so > I catch that too. The next day, it encounters a urllib2.HTTPError, then a > IOError, a socket.timeout, httplib.InvalidURL,... > > How do you program robustly with these modules throwing all those > different (and sometimes undocumented) exceptions at you? I do it by not micromanaging things. Presumably if you plan to catch an exception, you have a specific procedure in mind for handling the problem. Maybe a retry, maybe an alternate way of attempting the same thing? Look to the code that you are putting in those except: statements (or that you think you want to put in them) to decide what to do about this situation. If each type of exception will be handled in a different manner, then you definitely want to identify each type by looking at the source or the docs, or doing it empirically. Most of the time there isn't a whole lot of real "handling" going on in an exception handler, but merely something like logging and/or reporting it onscreen in a cleaner fashion than a traceback, then failing anyway. This is one reason Java does get it wrong: 95% of exceptions don't need and shouldn't have special handling anyway. Good code should probably have a very small set of real exception handling cases, and one or two catchalls at a higher level to avoid barfing a traceback at the user. > A catchall seems like a bad idea, since it also catches AttributeErrors > and other bugs in the program. Generally speaking this won't be a problem if you have your catchalls at a fairly high level and have proper unit tests for the lower level code which is getting called. You are doing unit testing, aren't you? ;-) -Peter From filipwasilewski at gmail.com Mon Mar 27 12:46:03 2006 From: filipwasilewski at gmail.com (filipwasilewski at gmail.com) Date: 27 Mar 2006 09:46:03 -0800 Subject: Difference between 'is' and '==' In-Reply-To: References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <4427d287$0$38669$edfadb0f@dread12.news.tele.dk> Message-ID: <1143481563.051879.40440@i40g2000cwc.googlegroups.com> Clemens Hepper wrote: > It's strange: python seem to cache constants from 0 to 99: That's true. The Python api doc says that Python keeps an array of integer objects for all integers between -1 and 100. See http://docs.python.org/api/intObjects.html. This also seems to be true for integers from -5 to -2 on (ActiveState) Python 2.4.2. -- fw From mogmios at mlug.missouri.edu Fri Mar 10 17:16:56 2006 From: mogmios at mlug.missouri.edu (Michael) Date: Fri, 10 Mar 2006 14:16:56 -0800 Subject: image letter recognition In-Reply-To: References: <1142013873.889402.142800@u72g2000cwu.googlegroups.com> Message-ID: <4411FAD8.9090806@mlug.missouri.edu> >> Is there an existing package for python that will perform simple letter >> recognition from image files? I'm specifically looking for a way to >> read from a png file, but that can be changed. >> > "simple letter recognition from image file" now there's an oxymoron. > > I've successfully used ExperVision's RTK OCR toolkit for Windows > from Python. Actually by using ctypes you should be able to call > any of the many OCR engines that are available. Alas, all that I > found that were really good were not free (but I haven't looked in > well over a year). > Might look at these: http://directory.fsf.org/claraocr.html http://directory.fsf.org/ocrad.html -- Michael McGlothlin, tech monkey Tub Monkey http://www.tubmonkey.com/ From paraic.gallagher at gmail.com Wed Mar 22 05:22:48 2006 From: paraic.gallagher at gmail.com (Paraic Gallagher) Date: Wed, 22 Mar 2006 10:22:48 +0000 Subject: Default/editable string to raw_input Message-ID: <44212578.7090005@gmail.com> Hi, This is my first post to the list, I hope somebody can help me with this problem. Apologies if it has been posted before but I have been internet searching to no avail. What I am trying to do is provide a simple method for a user to change a config file, for a test suite. The config file consists of a number of keys, eg. build number, target device, etc. What I would like to do is give the user a key, and the previous value for that key. The user can then accept the previous value or edit it on the line. I have a method where the previous value of a key is presented to the user and can be accepted if the user hits return. But as some of the values are somewhat long, and the user may only need to change 1 or 2 characters, it would be a nice feature to offer line editing. I can get the readline.set_pre_input_hook() function to send text after a raw_input prompt, but this text cannot be edited. Thanks in advance for any help. Paraic. From larry.bates at websafe.com Sat Mar 25 21:02:16 2006 From: larry.bates at websafe.com (Larry Bates) Date: Sat, 25 Mar 2006 20:02:16 -0600 Subject: noobie mkdir problem/question In-Reply-To: <1143322904.618585.188740@t31g2000cwb.googlegroups.com> References: <1143322904.618585.188740@t31g2000cwb.googlegroups.com> Message-ID: <4425F628.5020203@websafe.com> Except for the fact that I don't have any idea where "given" variable comes from. This works perfectly for me. It writes data into /xrefs/given.log perfectly. In the future you should cut/paste your code so we can see enough to help better. Here is my code with a few changes. import os import sys root = raw_input("Enter the path where the program should run: ") xrefs = os.path.join(root,'xrefs') if not os.path.exists(xrefs): os.makedirs(xrefs) else: sys.exit('LOG folder already exists. Exiting program.') outputFname = 'given.log' # You need to change this line outputFile = open(os.path.join(xrefs,outputFname), 'w') data="this is a test\n" outputFile.write(data) outputFile.close() -Larry Bates ProvoWallis wrote: > Hi, > > I'm trying to write a script that will create a new directory and then > write the results to this newly created directory but it doesn't seem > to work for me and I don't know why. I'm hoping someone can see my > mistake or at least point me in the right direction. > > I start like this capturing the root directory and making my new > "xrefs" directory (I can see the new folder in windows explorer): > > root = raw_input("Enter the path where the program should run: ") > > xrefs = os.path.join(root,'xrefs') > > if (os.path.isdir(xrefs) == 0): > os.mkdir(xrefs) > else: > sys.exit('LOG folder already exists. Exiting program.') > > ...I do everything else... > > And then I'm trying to write the results out to xrefs. But instead of > writing to xrefs they're written to the original directory, i.e., root. > and I'm not sure why. > > outputFname = given + '.log' > outputFile = open(os.path.join(xrefs,outputFname), 'w') > outputFile.write(data) > outputFile.close() > > Anyone? > > Thanks, > > Greg > From superlogan72 at hotmail.it Mon Mar 6 04:19:26 2006 From: superlogan72 at hotmail.it (Luca) Date: 6 Mar 2006 01:19:26 -0800 Subject: vb dll Message-ID: <1141636766.206500.196920@z34g2000cwc.googlegroups.com> Hello at all. I have to use a vb dll called ndxComm.dll I have do this but i get the following error: from win32com import client from win32com.client import Dispatch avatar = Dispatch("NdxComm") avatar.Reset(1, 20, True) pywintypes.com_error:(-2147221005, "stringa dell'interfaccia non valida.", None, None) frame4.py:avatar = Dispatch(NdxComm") _init_.py:dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) dynamic.py : return(_GetGoodDispatch(IDispatch, clsctx), userName) dynamic.py: IDspatch = pythoncom.CoCreateInstance(IDspatch, None, clsctx,pythoncom.IID_IDispatch) Can you help me to make it in the right way. Thanks for your help Regars From jo at durchholz.org Sat Mar 18 14:23:55 2006 From: jo at durchholz.org (Joachim Durchholz) Date: Sat, 18 Mar 2006 20:23:55 +0100 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: <1142695261.018806.58220@u72g2000cwu.googlegroups.com> References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1142695261.018806.58220@u72g2000cwu.googlegroups.com> Message-ID: wkehowski at cox.net schrieb: > "This is where K starts to set itself from apart from most of the > common programming languages in use today. You rarely write loops in K > (KDB is 100% loop-free), instead you use adverbs. An adverb modifies a > function, returning another function, changing the ways it operates > over its arguments and what it does with it's return values." Doesn't sound too different from what closures do. Or lazy parameter passing. I'm not sure whether the K designer actually fits that description, but there are too many language designers around reinventing the wheel, arguing whether it should have seven, eight or thirteen sides... Regards, Jo From aisaac0 at verizon.net Sun Mar 26 20:21:29 2006 From: aisaac0 at verizon.net (David Isaac) Date: Mon, 27 Mar 2006 01:21:29 GMT Subject: access mbx files? References: Message-ID: "Alan Isaac" wrote in message news:T9zVf.1942$b07.1558 at trnddc05... > Should I be able to access mail messages in Mahogany mail's mbx > format using the Python mailbox module? If so, can someone > please post a working example? If not, can you please > point me to documentation of the file format or better yet > Python code to parse it? OK, from what I have been able to learn (not a lot), my original question may boiled down to: has anyone wrapped the cclient library for Python? The answer to that appears to be yes: http://freshmeat.net/projects/python-cclient/ Will I need to pursue this, or is this functionality somewhere in the mailbox module. (And if not, can someone please explain why not?) Thanks, Alan Isaac From fredrik at dolda2000.com Mon Mar 6 22:37:07 2006 From: fredrik at dolda2000.com (Fredrik Tolf) Date: Tue, 07 Mar 2006 04:37:07 +0100 Subject: Checking function calls Message-ID: <1141702627.27803.40.camel@pc7.dolda2000.com> If I have a variable which points to a function, can I check if certain argument list matches what the function wants before or when calling it? Currently, I'm trying to catch a TypeError when calling the function (since that is what is raised when trying to call it with an illegal list), but that has the rather undesirable side effect of also catching any TypeErrors raised inside the function. Is there a way to avoid that? Fredrik Tolf From invalidemail at aerojockey.com Thu Mar 2 14:09:42 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 2 Mar 2006 11:09:42 -0800 Subject: how do you move to a new line in your text editor? In-Reply-To: References: <%ZGNf.1711$No6.40016@news.tufts.edu> <1141325510.264691.215260@t39g2000cwt.googlegroups.com> Message-ID: <1141326582.490436.125810@j33g2000cwa.googlegroups.com> John Salerno wrote: > Carl Banks wrote: > > John Salerno wrote: > >> So I'm wondering, how do you all handle moving around in your code in > >> cases like this? Is there some sort of consistency to these things that > >> you can write rules for your text editor to know when to outdent? It > >> doesn't seem like you can do this reliably, though. > > > > Emacs, at least, outdents reliably with spaces. Probably some other > > editors do as well, though I was kind of surprised to find out that > > some editors have (compared to Emacs) weak indent inference. > > > > If editing with spaces annoys you, it might be possible with your > > editor (which seems to have a variable tab stop) to edit the file with > > tabs, but save it with spaces. > > I use UltraEdit right now, and it is possible to convert spaces and tabs > back and forth, but it's just an extra step. I was thinking about trying > vim, as I've heard it's easier to learn than emacs. Well, they don't call vi the "Very Intuitive" editor for nothing. I suspect if you're not used to the modes and movement keys and stuff it'll be a little steep learning at first. More power to you if you can get used to that. You wouldn't know if Ultraedit has some kind of hook mechanism (whereby it can execute a macro or script or something upon loading/saving). That could solve your problem. Obviously, having to manually convert isn't too helpful. Carl Banks From rschroev_nospam_ml at fastmail.fm Thu Mar 9 14:38:21 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 09 Mar 2006 19:38:21 GMT Subject: A bit OT: Python prompts display as nested mail quotes in Thunderbird In-Reply-To: References: Message-ID: Joel Hedlund schreef: > Hi > > Sorry to bother you with my OT problems, but my newsgroup reader > (Thunderbird) displays explicitly written python prompts as triple > nested mail quotes (with lines in alternating colors in the margins). > That's pretty tiresome to look at in a python newsgroup. Therefore, I'm > looking for a way to display messages from this newsgroup *In Plain Text*. > > Has anyone else encountered/solved this problem? Should I get another > newsgroup reader? In that case, which? I'm running Thunderbird 1.0.7 on > Ubuntulinux 5.10. I have the same problem, but it doesn't bother me that much. However, a workaround could be pressing CTRL-U (or View > Message Source); that brings up the source of the message, with no colors applied to the quotes. Do you have the Quote Colors extension? It has an option 'Enable graphical quoting for plain text messages'. If you uncheck that, Thunderbird will use normal quote characters for plain text messages. You can also disable the use of colors in the options, but that will remove the colors for all messages. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From s323 at mail.ru Thu Mar 2 06:53:31 2006 From: s323 at mail.ru (Sergey) Date: Thu, 2 Mar 2006 14:53:31 +0300 Subject: why? [win32com/WMI] References: Message-ID: "Tim Golden" wrote in message news:mailman.2569.1141231029.27775.python-list at python.org... [Sergey] >import wmi >c = wmi.WMI (computer="srv", user="Admin at zzz.ru", password="****") >pid, retval = c.Win32_Process.Create (CommandLine="notepad.exe") Wonderful... It works. But I tryed the module, by the sample from help(wmi): >>> remote_process = wmi.WMI (computer="pms-dc", user="...", password="...").new ("Win32_Process") And got: Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\Lib\site-packages\wmi.py", line 624, in new return getattr (self, class_name).new (**kwargs) File "C:\Python24\Lib\site-packages\wmi.py", line 539, in new obj.set (**kwargs) File "C:\Python24\Lib\site-packages\wmi.py", line 394, in set handle_com_error (error_info) File "C:\Python24\Lib\site-packages\wmi.py", line 199, in handle_com_error raise x_wmi, "\n".join (exception_string) wmi.x_wmi: -0x7ffdfff7 - Exception occurred. Error in: SWbemObjectEx -0x7ffbefdc - Provider is not capable of the attempted operation So I decided to fallback to clean COM. From phpbird at gmail.com Sat Mar 18 07:37:25 2006 From: phpbird at gmail.com (JuHui) Date: 18 Mar 2006 04:37:25 -0800 Subject: what the best way to get 1000 page on same server? Message-ID: <1142685445.792380.25900@u72g2000cwu.googlegroups.com> Hi : I want to get many html page on same server. I have tried httplib and urllib. I think httplib is better one because it's httplib.HTTPConnection. It will establish one network connection then do other opration before connection close. The urllib will establish network connection each time request. Am I wrong? How about urllib2? how about a new socket client for this requirement? is there any other lib shall I use for this requirement? Any suggestion are welcome. From grflanagan at yahoo.co.uk Tue Mar 21 17:25:44 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 21 Mar 2006 14:25:44 -0800 Subject: NOT Python: Taxonomy list reference In-Reply-To: <44206b1f$1@nntp.zianet.com> References: <44206b1f$1@nntp.zianet.com> Message-ID: <1142979944.805907.87290@v46g2000cwv.googlegroups.com> ej wrote: > I hope you will forgive this being a bit off subject, but this is about > the smartest list of people I know. I came across a list in the past while > studying OO methdology stuff. The list was trying to make the point of the > problem classification systems often run into (i.e., often things belong in > more than one group simultaneously). > > The list reads something like this: > > 1. Beasts that belong to the king > 2. Great beasts > 3. Furry beasts > 4. Unicorns and other magical beasts. > 5. Beasts with four hooves. > ... Footnote (even further off-topic)- cf. the preface to 'The Order of Things', Michel Foucault: This book first arose out of a passage in Borges, out of the laughter that shattered, as I read the passage, all the familiar landmarks of my thought - our thought, the thought that bears the stamp of our age and our geography - breaking up all the ordered surfaces and all the planes with which we are accustomed to tame the wild profusion of existing things, and continuing long afterwards to disturb and threaten with collapse our age-old distinction between the Same and the Other. This passage quotes a 'certain Chinese encyclopedia' in which it is written that 'animals are divided into: (a) belonging to the Emperor, (b) embalmed, (c) tame, (d) sucking pigs, (e) sirens, (f) fabulous, (g) stray dogs, (h) included in the present classification, (i) frenzied, (j) innumerable, (k) drawn with a very fine camelhair brush, (l) et cetera, (m) having just broken the water pitcher, (n) that from a long way off look like flies'. ...The central category of animals 'included in the present classification', with its explicit reference to paradoxes we are familiar with, is indication enough that we shall never succeed in defining a stable relation of contained to container between each of these categories and that which includes them all: if all the animals divided up here can be placed without exception in one of the divisions of this list, then aren't all the other divisions to be found in that one division too? And then again, in what space would that single, inclusive division have its existence? Absurdity destroys the *and* of the enumeration by making impossible the *in* where the things enumerated would be divided up... ...I use that word [operating-table] in two superimposed senses: the nickel-plated, rubbery table swathed in white, glittering beneath a glass sun devouring all shadow...; and also a table, a tabula, that enables thought to operate upon the entities of our world, to put them in order, to divide them into classes, to group them according to names that designate their similarities and their differences - the table upon which, since the beginning of time, language has intersected space... ---------------------------------------------------------------------------------------- No, I didn't type that out ;-): http://serendip.brynmawr.edu/sci_cult/evolit/s05/prefaceOrderFoucault.pdf Gerard From jjl at pobox.com Thu Mar 23 13:25:57 2006 From: jjl at pobox.com (John J Lee) Date: Thu, 23 Mar 2006 18:25:57 +0000 (GMT Standard Time) Subject: python-announce moderation (was: Re: ANN: ClientForm 0.2.2 released) In-Reply-To: References: Message-ID: Hmm, hschilling at nasa.gov, who are you? python-announce moderator? I didn't put you on my To: line (nor python-list for that matter, but I guess that's a reasonable place for it to go...). Also FYI, it ended up going to wwwsearch-general twice, I guess because the you (or the moderation software) forwarded it there after moderation, which isn't really necessary. John On Wed, 22 Mar 2006, John J Lee wrote: > http://wwwsearch.sourceforge.net/ClientForm/ > > This is the first stable release of ClientForm 0.2. > > (See below for the list of changes since 0.2.1b.) > > Many improvements have been made as part of the 0.2 release, thanks > largely to Gary Poster, Benji York and their employer Zope Corporation > as part of their work on zope.testbrowser. These include: > > * 0.1 backwards compatibility mode (backwards_compat switch). > * Greatly improved support for labels, including control labels. > * Added first-class support for list items and labels. > * A few methods have been added, and many superfluous methods > deprecated. > * The example script on the web page / README.html is now an > executable script in the examples directory, that runs against a > test page on the wwwsearch.sourceforge.net site. > * Label matching is now by substring (after compression of > whitespace), not by exact string equality. > * Support for list item ids. > * Finding controls or items now raises AmbiguityError if no nr > argument is supplied and the other arguments do not uniquely > identify the control or item. The old behaviour is restored by > passing nr=0. > * Fix multiple identical list item behaviour. > * Fixed a bug where disabled list items were successful (got sent back > to the server). > * More intuitive disabled list item behaviour. > * Large sections of the module have been reimplemented using classes > Item and Label, making for better code. > * Added ListControl.get(), ListControl.get_items(), > HTMLForm.set_value_by_label(), and HTMLForm.get_value_by_label() > methods. > * Applied patch from Titus Brown to add .clear() method to all > Controls. > * The following ListControl methods have been deprecated: > possible_items > get_item_attrs > set_item_disabled > get_item_disabled > set_single > toggle_single > set > toggle > * The following HTMLForm methods have been deprecated: > possible_items > set_single > toggle_single > set > toggle > * The by_label argument of the following methods has been deprecated: > get_value > set_value > * Added support for setuptools / EasyInstall / Python Eggs. > * Make entitydefs more sane. Expose entitydefs in ParseFile / > ParseResponse functions. > > > Changes since 0.2.1b: > > * Fixes to setup.py &c. > * Follow IE and Firefox on algorithm for choosing MIME boundary -- > servers are buggy on this. > * Fix POST multipart/form-data parameter ordering (patch from > Balazs Ree) and ImageControl ordering. > * Fix .fixup() of disabled select with no selected options (John > Wayne). > * Encoding fixes. > * Add BeautifulSoup support (not yet well tested). > * Switch from htmllib to sgmllib. > * Add form name to str(HTMLForm). > * Make parser debugging a bit easier. > > > Requires Python 2.0 or newer. > > ClientForm is a Python module for handling HTML forms on the client > side, useful for parsing HTML forms, filling them in and returning the > completed forms to the server. It developed from a port of Gisle Aas' > Perl module HTML::Form, from the libwww-perl library, but the > interface is not the same. > > Simple example: > > from urllib2 import urlopen > from ClientForm import ParseResponse > > forms = ParseResponse(urlopen("http://www.example.com/form.html"), > backwards_compat=False) > form = forms[0] > print form > form["author"] = "Gisle Aas" > > # form.click() returns a urllib2.Request object > # (see HTMLForm.click.__doc__ if you don't have urllib2) > response = urlopen(form.click("Thanks")) > > > John > > > ------------------------------------------------------- > This SF.Net email is sponsored by xPML, a groundbreaking scripting language > that extends applications into web and mobile media. Attend the live webcast > and join the prime developer group breaking into this new coding territory! > http://sel.as-us.falkag.net/sel?cmd=lnk&kid=110944&bid=241720&dat=121642 > _______________________________________________ > wwwsearch-general mailing list > wwwsearch-general at lists.sourceforge.net > https://lists.sourceforge.net/lists/listinfo/wwwsearch-general > > From timr at probo.com Thu Mar 9 03:09:09 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 09 Mar 2006 08:09:09 GMT Subject: It is fun.the result of str.lower(str()) References: <1141716968.656842.57100@v46g2000cwv.googlegroups.com> Message-ID: "Sullivan WxPyQtKinter" wrote: > >Guess what would be the result of these functions: > >>>>str.lower('ASFA') >>>>str.join(str(),['1','1','1']) >>>>str.join('a','b') > >If you guess them correctly, please explain. Can you tell us what you expected these to do? It might help future questioners. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From rabkin at mweb[DOT]co[DOT]za Sun Mar 26 08:14:56 2006 From: rabkin at mweb[DOT]co[DOT]za (Max) Date: Sun, 26 Mar 2006 15:14:56 +0200 Subject: detecting drives for windows and linux In-Reply-To: References: <3uGdnTOPm5PGCrjZnZ2dnUVZ_u2dnZ2d@adelphia.com> <1143317936.422335.294230@u72g2000cwu.googlegroups.com> Message-ID: BWill wrote: > oh, I wasn't expecting a single solution for both platforms, just some > good solutions > > thanks Are you aware that this idea is somewhat foreign to Linux? (Maybe you are and want to do it anyway?) Linux puts the whole file system (including mounted iPods, ISOs and NTFS drives) in one hierarchy. --Max From mnations at gmail.com Fri Mar 17 18:40:54 2006 From: mnations at gmail.com (Mudcat) Date: 17 Mar 2006 15:40:54 -0800 Subject: Need design advice. What's my best approach for storing this data? In-Reply-To: References: <1142615283.733346.74260@i40g2000cwc.googlegroups.com> Message-ID: <1142638854.311089.6310@p10g2000cwp.googlegroups.com> >On a different tack, to avoid thinking about any db issues, consider >subscribing >to TC2000 (tc2000.com)... they already have all that data, >in a database which takes about 900Mb when fully installed. That is an interesting option also. I had actually looked for ready made databases and didn't come across this one. Although, I don't understand how they can fit all that info into 900Mb. I like this option, but I guess if I decide to keep using this database then I need to keep up my subcription. The thing I liked about downloading everything from Yahoo was that I didn't have to pay anyone for the data. Does anyone know the best way to compress this data? or do any of these databases handle compression automatically? 5gig will be hard for any computer to deal with, even in a database. From johnjsal at NOSPAMgmail.com Thu Mar 2 15:48:04 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 02 Mar 2006 20:48:04 GMT Subject: do design patterns still apply with Python? Message-ID: <8SINf.1718$No6.40137@news.tufts.edu> Since Python does so many things different, especially compared to compiled and statically typed languages, do most of the basic design patterns still apply when writing Python code? If I were to read a design pattern book (such as Head First Design Patterns), could I apply their Java examples to Python easily enough, or does Python require a different perspective when applying patterns? From donk71 at gmail.com Wed Mar 15 17:43:31 2006 From: donk71 at gmail.com (donk71 at gmail.com) Date: 15 Mar 2006 14:43:31 -0800 Subject: State of SSL in Python Message-ID: <1142462611.164759.38810@v46g2000cwv.googlegroups.com> I was searching the net about SSL support in Python, and it seems that a few years ago that the native SSL functions were broken or badly wanting in comparison to third party libraries such as m2crypto, POW and pyOpenSSL. What is the state of native support now? I'd like to use Python's native SSL functions because I'd like to keep the install requirements at a minimum. I'm writing a client that will use TLS with X509 certificate validation (and CRL checking in the future). Will Python be able to handle it? From sybrenUSE at YOURthirdtower.com.imagination Fri Mar 3 04:18:12 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 3 Mar 2006 10:18:12 +0100 Subject: white space in expressions and argument lists References: Message-ID: rtilley enlightened us with: > I took it literally when I first read it b/c it made sense to me and > I did not notice the date. I don't think it will ever be _required_ > of all Python hackers, but I may be wrong. Well, part of it is a serious PEP. It being _required_ was the joke. 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 neurogasm at gmail.com Fri Mar 24 20:44:25 2006 From: neurogasm at gmail.com (Kun) Date: Fri, 24 Mar 2006 20:44:25 -0500 Subject: newbie parsing question In-Reply-To: <1143247662.544559.165060@t31g2000cwb.googlegroups.com> References: <1143247662.544559.165060@t31g2000cwb.googlegroups.com> Message-ID: raviteja.bhupatiraju at gmail.com wrote: > Use Regular expressions > http://docs.python.org/lib/module-re.html > i tried to parse (below) with the regular expression: emails = re.findall('\S*\s(\w+@\w+\.\w+)', senders) and got the following error: Traceback (most recent call last): File "/Life/School/Homework/Spring 2006/OPIM 399/Tutorial/IMAP/scannermailer.py", line 19, in -toplevel- emails = re.findall('\S*\s(\w+@\w+\.\w+)', senders) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/sre.py", line 167, in findall return _compile(pattern, flags).findall(string) TypeError: expected string or buffer any help would be appreciated. [('460 (BODY[HEADER.FIELDS (FROM)] {46}', 'From: Kevin Feng \r\n\r\n'), ')', ('461 (BODY[HEADER.FIELDS (FROM)] {37}', 'From: Kevin \r\n\r\n'), ')'] From dmieluk at exemail.com.au Mon Mar 13 09:13:40 2006 From: dmieluk at exemail.com.au (Dave) Date: Tue, 14 Mar 2006 01:13:40 +1100 Subject: Speed of data structures in python In-Reply-To: References: Message-ID: As the OP, i thought i'd follow up with my experience, in case anyone else is learning pyopengl and as mystified as i was (am?). Thank you to all the posters who responded, especially the one who mentioned display lists... Initially, i had built a very simple prototype, getting 5 fps. This was very poorly designed though, calculating normals and positions (sqrt, sin, pow) on the fly. when i posted the OP, i suspecteded that the biggest improvement would be achieved by storing the normals and positions in the fastest data structure. after posting, i implemented numpy arrays to hold normals and positions, and got 18 fps. i then increased the complexity of the protoype to the bare-min specs required, and got 1-2 fps. i then implemented display lists (opengl stuff), and am now getting 190 fps (on the larger protoype). so, my point is, the limiting factor had nothing to do with speed of data structures in python, but the way data was being consumed by opengl (and my absolute newbieness at opengl ;-) i hope this helps anyone who is learning similar material Dave On Sat, 11 Mar 2006 16:54:06 +1100, Steven D'Aprano wrote: > On Fri, 10 Mar 2006 21:06:27 -0600, Terry Hancock wrote: > >> On Sat, 11 Mar 2006 13:12:30 +1100 >> "Steven D'Aprano" wrote: >>> On Fri, 10 Mar 2006 23:24:46 +1100, Dave wrote: >>> > Hi. I am learning PyOpenGL and I am working with a >>> > largish fixed scene composed of several thousand >>> > GLtriangles. I plan to store the coords and normals in >>> > a NumPy array. >>> > >>> > Is this the fastest solution in python? >> >>> Optimization without measurement is at best a waste of >>> time and at worst counter-productive. Why don't you time >>> your code and see if it is fast enough? >>> >>> See the timeit module, and the profiler. >> >> Talk about knee-jerk reactions. ;-) > > Yes, let's. > >> It's a *3D animation* module -- of course it's going to be >> time-critical. Sheesh. Now *that* is stating the obvious. > > Did I say it wasn't? I asked if the current solution is fast enough. If > the current solution is fast enough, then why waste time trying to speed > it up? Does the Original Poster think that PCs will get slower in the > future? > > >> The obvious solution is actually a list of tuples. > > But that's not the solution being asked about, nor did I suggest it. > > >> But >> it's very possible that that won't be fast enough, so the >> NumPy approach may be a significant speedup. I doubt you >> need more than that, though. > > I didn't argue against the NumPy approach. I suggested that, instead of > *asking* if there was something faster, the O.P. should actually *try it* > and see if it is fast enough. > > If you think that is bad advice, please tell us what you consider good > advice. > > > -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From aleaxit at yahoo.com Fri Mar 10 22:10:24 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 10 Mar 2006 19:10:24 -0800 Subject: Why property works only for objects? References: <1hbyfgj.a3p39r1smomavN%aleaxit@yahoo.com> <4412107a$0$22499$636a55ce@news.free.fr> Message-ID: <1hbzzh7.1qlkv8hokpiqzN%aleaxit@yahoo.com> Michal Kwiatkowski wrote: ... > I'm trying to understand attributes lookups made by Python, having > properties and special methods in mind. So far I've come up with kind of > reasoning I've coded below. I would appreciate any comments and > suggestions. First, let's forget legacy-style classes, existing only for backwards compatibility, and focus on new-style ones exclusively -- never use legacy classes if you can avoid that. Descriptors come in two varieties: overriding and non-overriding. Both kinds have a __get__ method (that's what makes them descriptors). Overriding ones also have a __set__, non-overriding ones don't. (Until pretty recently, the two kinds were known as data and non-data, but the new terminology of overriding and non-overriding is much clearer). I covered descriptors in one of my talks at Pycon '05 and elsewhere; you can find just about all of my talks by starting at www.aleax.it (mostly just PDF forms of the slides in my presentations). I cover them in quite a central role in the forthcoming 2nd edition of Python in a Nutshell, too. But, summarizing: overriding descriptors are FIRST looked up in the class (class overrides instance); non-overriding descriptors, first in the instance (class does not override). Functions are NON-overriding descriptors. Special methods IMPLICITLY looked up by Python ALWAYS go to the class ONLY -- adding an x.__getitem__ per-class attribute that happens to be callable doesn't mean that attribute is gonna handle z=x[y] and the like (in legacy-style classes the rule was different, but that led to a host of complications that we're much better off without!). Alex From mahs at telcopartners.com Sun Mar 19 20:38:27 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Sun, 19 Mar 2006 17:38:27 -0800 Subject: String comparison question In-Reply-To: <400BDC416E2A0042AA35DF3919BB8A5115E648@mail.mtl.proksim.com> References: <400BDC416E2A0042AA35DF3919BB8A5115E648@mail.mtl.proksim.com> Message-ID: Olivier Langlois wrote: > I would like to make a string comparison that would return true without > regards of the number of spaces and new lines chars between the words > > like 'A B\nC' = 'A\nB C' > import string NULL = string.maketrans("","") WHITE = string.whitespace def compare(a,b): """Compare two strings, disregarding whitespace -> bool""" return a.translate(NULL, WHITE) == b.translate(NULL, WHITE) Here, str.translate deletes the characters in its optional second argument. Note that this does not work with unicode strings. Michael From no-spam at no-spam-no-spam.com Sat Mar 11 19:14:33 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sun, 12 Mar 2006 01:14:33 +0100 Subject: Global Lock for Python Threading ? - Re: "RuntimeError: dictionary changed ... In-Reply-To: References: <104lhpbuofu4l.jz32d3oa1uk7$.dlg@40tude.net> Message-ID: robert wrote: > > Guess it would be more wise to not expose deepcopy, cPickle.dump etc. to > this kind of RuntimeError unnecessarily. > The speed gain of the iterator-method - if any - is minor, compared to > the app crash problems, which are not easy to discover and work-around > (because they happen rarely on fast computers). searched the thread, threading module for a function for generally locking/dislocking all other python threads from execution. Did not find something like that. (That would be very useful in some threading applications to protect critical sections without forcing the whole application to be populated with lock objects. Of course, such function should be used with care (and "finally") - but it should be there to make thread programming easier...) Robert From dthierbach at usenet.arcornews.de Sat Mar 25 04:29:54 2006 From: dthierbach at usenet.arcornews.de (Dirk Thierbach) Date: Sat, 25 Mar 2006 10:29:54 +0100 Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1143024937.827420.104100@i39g2000cwa.googlegroups.com> <20060322141400.1A00.1.NOFFLE@dthierbach.news.arcor.de> <1143110872.284192.325230@u72g2000cwu.googlegroups.com> <20060323134326.C29.0.NOFFLE@dthierbach.news.arcor.de> <1143134775.887696.5000@z34g2000cwc.googlegroups.com> <20060323212800.79D.0.NOFFLE@dthierbach.news.arcor.de> <1143193333.963153.23850@g10g2000cwb.googlegroups.com> <20060324105346.10AF.0.NOFFLE@dthierbach.news.arcor.de> <1143221565.921043.312080@z34g2000cwc.googlegroups.com> Message-ID: <20060325092954.60C.0.NOFFLE@dthierbach.news.arcor.de> Dinko Tenev wrote: > Dirk Thierbach wrote: > [A lot of stuff] >> Now clearer? > Let's leave it there, and take a break. Maybe it would help to just take a concrete example, and work through it. Then you'll see exactly what happens. - Dirk From irmen.NOSPAM at xs4all.nl Fri Mar 24 19:55:23 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sat, 25 Mar 2006 01:55:23 +0100 Subject: How do I handle # In-Reply-To: References: Message-ID: <442494fe$0$24373$e4fe514c@news.xs4all.nl> Michael Sperlle wrote: > I need to write out a file containing the # comment. When I try to specify > it as part of a literal, everything afterward turns into a comment. > > I finally created a file containing the #, read it in, and used the > resulting variable as part of the string I created. > > But that is so kludgy, even a newbie like me is ashamed to use it, though > I did. > > Supposedly, I can us \x followed by the hex equivalent and somehow make > that work. > > Can anybody give an example of this; my attempts failed. Failed in what strange way? I don't see a problem at all: >>> open("bla.txt",'w').write("# some line with a hash comment\n") >>> open("bla.txt").read() '# some line with a hash comment\n' --Irmen From ptmcg at austin.rr._bogus_.com Wed Mar 29 01:45:20 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 29 Mar 2006 06:45:20 GMT Subject: any() and all() on empty list? References: <7x3bh1x0ym.fsf@ruckus.brouhaha.com> Message-ID: <42qWf.18211$uX5.7574@tornado.texas.rr.com> "Paul Rubin" wrote in message news:7x3bh1x0ym.fsf at ruckus.brouhaha.com... > "Steve R. Hastings" writes: > > In the all() example, if there *are* no values in S, then none of the > > values can be != 0, and IMHO all() should return False. > > That goes against the usual meaning of "all" in, say, mathematical logic. > > Usually, "for all X in S, PRED(x) is true" means: > there does not exist X in S so that PRED(x) is false. > How do you get this "usually" stuff? I would agree that this is usually implemented as a short-circuited loop through the list, that breaks out at the first False value. But I would not be quick to equate "commonality of implementation" with "meaning". > So, all(empty sequence) should be true. "should be"? Or "usually turns out to be"? To my mind, the *meaning* of all() is that every element in the list asserts True. But this is with an initial assumption that all() is False, unless I test every value and find them to be True. Since I assume False to begin with, I get no values in the list to contradict the assumption, and so all([]) returns False. It would seem that the resolution rests on which initial condition we choose, False or True. Perhaps we should consult a more formal mathematical resource for this. -- Paul "If it was so, it might be; and if it were so, it would be; but as it isn't, it ain't. That's logic." From s99999999s2003 at yahoo.com Thu Mar 23 00:06:39 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 22 Mar 2006 21:06:39 -0800 Subject: removing file by inode Message-ID: <1143090399.430131.224390@t31g2000cwb.googlegroups.com> hi this is pertain to unix environment. is it possible to remove a file by it's inode and not it's filename using Python? Just curious... thanks. From userprogoogle-139 at yahoo.co.uk Thu Mar 23 09:26:18 2006 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: 23 Mar 2006 06:26:18 -0800 Subject: Server applications - avoiding sleep In-Reply-To: <2tOdnVuopvpdOoDZnZ2dnUVZ_vidnZ2d@comcast.com> References: <1142429205.440380.294650@z34g2000cwc.googlegroups.com> <2tOdnVuopvpdOoDZnZ2dnUVZ_vidnZ2d@comcast.com> Message-ID: <1143123978.845606.53280@e56g2000cwe.googlegroups.com> Hi Lev, Sounds interesting. As I am quite new to Python an example program would be most welcome. My email address is contained in the message. Best, rod From dont_bug_me at all.uk Wed Mar 29 18:23:16 2006 From: dont_bug_me at all.uk (Jeff) Date: Wed, 29 Mar 2006 23:23:16 GMT Subject: Content Management System In-Reply-To: <1143627824.174540.13710@z34g2000cwc.googlegroups.com> References: <1143627824.174540.13710@z34g2000cwc.googlegroups.com> Message-ID: Water Cooler v2 wrote: > I know what it is, and yet the knowledge of what a CMS is, is so vague > that I find myself asking this question every now and then. I've > googled and read the resources too. However, the knowledge is still not > clear. It is so vague. > > > Me: Just what is a content management system? There's many different CMS sytems out there. How they work vary widely. But basically it's about making the site maintainable. Creating pages ad hoc on your desktop can lead to variations in a website depending on when and who made that page. That can cause problems as a site expands. Let's talk about web based. Common and necesary features are: 1) A Page Manager that shows you the site structure and lets you add edit or move pages about the site. Since this is stored in an online database, everyone who needs to edit the site will have the same data. That's an advantage over having this on your desktop where syncing the data is necesary. 2) A page editor. The idea here is to seperate the content from the presentation. Typically the content will be plugged into a template(s) that conforms to your site so that all pages will have the same look and feel. If you need to make a change sitewide, changing the template(s) will do that,other than making changes one page at a time. What you want is to seperate content from presentation. You want your pages to be reasonable HTML instead of what an inexperienced (or even experienced) might create on their own. 3) Navigation. CMS should be able to update your navigation as you add pages, or move them. 4) Controlling access to editing and making navigation changes. This can be by directory, subdirectory or even page. I usually see the first two, sometimes an editor will need to to have access to different sections of the site, but not to the whole site. Sometimes this will need to be reviewed by an administrator. Every site tends to have differing needs. 5)Ability to upload PDF's, word docs, etc... and link them into your site. Usually you will want to do this online, rather than having to FTP content up, typically you don't want CMS users to even have to know about FTP. So you want your CMS to be easy for the html illiterate to use, you want to be able to make sitewide changes easily, you want your navigation to automatically update and you want to be able to control access and if necesaary review changes. > > Myself: A place where content can be stored. Online in a structured place, this usually involves a database in some way. How that all works should be something you don't need to know or worry about. > > Me: OK. So, then what's a file system? > > Myself: That's not web-based. File-Systems are desktop-based. Everything is file based, even database tables. HTH, Cheers, Jeff > > Me: You can have a file-system on a common network server. I can even > have a network server and give remote access to people over a VPN. I > can host content on a terminal server, I can give them VNC clients, or > an RDP client, and let them browse what they want to. > > Myself: How will they know "where" to find what? > > Me: Come again? > > Myself: With all those avenues you mentioned, you won't publish > content. There will not be a taxonomy. You will just be dumping files > on another remote server. How will the users "find" what they want? > > > > So, is a CMS all about: > > 1. Taxonomy > 2. Publishing content in a Web based format > > Me: What about binary objects that cannot be published in HTML? > > Myself: Yeah! What about them, dude? Use your head. What about them? > Heard of a hyperlink? Heard of HTTP? FTP? No? > > Me: OK. I get it. But...I *still* don't get it, man. Why did we need > this? More importantly, where are the boundaries? I believe CMS also > lets users edit and publish content on-the-fly. > > > So, again, where are the boundaries? What about non-public content? > What about access rights? Do you have seperate users on CMS's having > their seperate folders as well, where they could put their own private > content? Or, is the idea behind CMS about "sharing" and so they put > only that which they need to share and not the private stuff. > > Do CMS's also allow access rights or authorization levels *per* > resource/file/unit of content that is uploaded on to them? Or, are they > role-based - e.g all users of this group will be able to access all > files, and users of that group will have read-only access to this > website. > From jzgoda at o2.usun.pl Wed Mar 8 15:51:16 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 08 Mar 2006 21:51:16 +0100 Subject: RAD tutorials and tools for GUI development with Python? In-Reply-To: References: <16de708d0603080251t3f62958btea3e13535bc4312c@mail.gmail.com> Message-ID: Michael Ekstrand napisa?(a): > Glade + PyGTK + libglade does the trick. libglade (exposed as gtk.glade > in Python) allows you to load Glade interface files (the raw XML Glade > saves your interfaces as) and then connect to various signals, access > the widgets, etc. > > About as fast as anything I've found. Much slicker than VB (the only > previous RAD experience I'd had that I could actually do anythin in). GTK on Windows looks worse than wx, but is easier to program. Anyway, it is not as easy as, say, Delphi. -- Jarek Zgoda http://jpa.berlios.de/ From deets at nospam.web.de Mon Mar 13 14:03:56 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 13 Mar 2006 20:03:56 +0100 Subject: Tkinter / Mac OS X Question (Aqua vs. X11) In-Reply-To: <1142221196.977709.229710@i39g2000cwa.googlegroups.com> References: <1142183130.539954.208070@i39g2000cwa.googlegroups.com> <47ji8fFff8o2U1@uni-berlin.de> <1142221196.977709.229710@i39g2000cwa.googlegroups.com> Message-ID: <47lu0sFgccqjU1@uni-berlin.de> dmsbox2000-list1 at yahoo.com schrieb: >> Install python using fink, and invoke that. Should work against X11 for >> all GUI-Toolkits. > > I prefer not to do this. Darwin is already a Unix, and Apple provides > a version of X11 that works well with it. > Fink seems like an > unecessary layer that I would rather not mess with. Tcl/Tk has a very > simple way to select. It would be nice if Python did something similar > (command line option, an environment variable, whatever). Fink works precisely _because_ OS X is a unix & has a X11 server. It is no "layer", it is just precompiled package management for unix-software running under OS X. > I looked for > an option in the build process, and from what I can tell, the OS X > version looks like it only builds a single version (TkAqua). > TkAqua and TkX11 do differ, and it would be nice to see the same script > run under both Aqua and X11 without having to switch machines. You might be able to tamper with the build process - but I have no idea how to do so. Diez From avenpace at gmail.com Sun Mar 19 14:11:54 2006 From: avenpace at gmail.com (avenpace at gmail.com) Date: 19 Mar 2006 11:11:54 -0800 Subject: python cgi permision error In-Reply-To: <1142658686.368333.283820@j33g2000cwa.googlegroups.com> References: <1142632787.589836.169330@u72g2000cwu.googlegroups.com> <1230270.90irRtrMbI@teancum> <1142658686.368333.283820@j33g2000cwa.googlegroups.com> Message-ID: <1142795514.411601.261560@t31g2000cwb.googlegroups.com> Sorry accidently replying using my other google account devilandme at gmail.com wrote: > > > > assuming you are running this python script the standard cgi way and not > > through modpython or fastcgi. > yes I'm running it in standard cgi way coz my provider only allow me > that way. And it's really just simple script. Sorry for the dumb question, I know modpython but what do you mean by fast cgi > > > > > try debugging this way. > > > > execute the python script from command line as the web user. > > > > make sure your python script prints the standard > > > > """Content-type: text/html > > > > """ > Yess I've done that. I have also run it on windows machine and it work. It seem my apache from SuSE 10.0 had some weird error permision that I don't understand when running cgi. I'm also had that kinda error if I running other cgi on perl or binary cgi :( From joe.hrbek at gmail.com Sun Mar 19 00:21:47 2006 From: joe.hrbek at gmail.com (joe.hrbek at gmail.com) Date: 18 Mar 2006 21:21:47 -0800 Subject: strange math? Message-ID: <1142745707.384085.42050@i39g2000cwa.googlegroups.com> Hello everyone, I'm experimenting with python and i'm following this tutorial: http://docs.python.org/tut/node6.html#SECTION006400000000000000000 I'm in section 4.7.5 Lambda Forms. In this section I was working along and I noticed something strange. It happened because of a typo. Below is a copy/paste from my idle session: >>>def make_incrementor(n): return lambda x: x+n >>>f=make_incrementor(42) >>>f(0) 42 >>>f(1) 43 >>>f(10) 52 >>>f(0) 42 >>>f(01) 43 >>>f(02) 44 >>>f(010) 50 >>>42+010 50 The first f(01) was a mistake. I accidentally forgot to delete the zero, but to my suprise, it yielded the result I expected. So, I tried it again, and viola, the right answer. So, I decided to really try and throw it for a loop, f(010), and it produced 50. I expected 52 (42+10). Why doesn't python ignore the first zero and produce a result of 52? It ignored the first zero for f(01) and f(02). Hmm. I know, I know, why am I sending it a 01,02, or a 010 to begin with? Like I said, it was an accident, but now i'm curious. I'm not a computer science major so please be kind with any explanations. From ianare at gmail.com Mon Mar 13 13:16:12 2006 From: ianare at gmail.com (=?iso-8859-1?B?aWFuYXLp?=) Date: 13 Mar 2006 10:16:12 -0800 Subject: suse linux 10 and wx.listctrl display issues In-Reply-To: References: <1141799391.412666.160650@j52g2000cwj.googlegroups.com> <1141801934.075608.68840@j33g2000cwa.googlegroups.com> Message-ID: <1142273771.939082.117790@p10g2000cwp.googlegroups.com> Well that definitly works, thanks. Is there any way to keep the themes though? From wkehowski at cox.net Sun Mar 19 00:22:42 2006 From: wkehowski at cox.net (wkehowski at cox.net) Date: 18 Mar 2006 21:22:42 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: <1142698086.042262.161710@z34g2000cwc.googlegroups.com> References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <8764medlhm.fsf@qrnik.zagroda> <1142556358.098924.59180@e56g2000cwe.googlegroups.com> <1142559980.525680.282250@u72g2000cwu.googlegroups.com> <1142698086.042262.161710@z34g2000cwc.googlegroups.com> Message-ID: <1142745762.520932.275840@u72g2000cwu.googlegroups.com> OK, a bad case of RTFM. I saved your file as WildCartesian.hs and then 1) command line: ghci WildCartesian.hs 2) Get some loading messages 3) command line: test and it works! But how do I compile it to get a program with command line arguments? I'm looking through Daume's tutorial right now. From annaraven at gmail.com Mon Mar 13 12:29:38 2006 From: annaraven at gmail.com (Anna Ravenscroft) Date: Mon, 13 Mar 2006 09:29:38 -0800 Subject: Announcing edupython list Message-ID: In order to facilitate small groups working on specific Python-in-Education projects, we have launched an edupython list on google groups (http://groups.google.com/group/edupython or edupython at googlegroups.com). We envision participation by people trying to coordinate work on the nuts and bolts implementation of a project, with frequent progress reports and requests for suggestions and comments coming back to edu-sig. The list developed as a result of a quite well-attended and enthusiastic BOF meeting at PyCon. This edupython list is not intended to replace edu-sig, which remains very strong for theoretical and philosophical discussions, and for getting input and suggestions from a wider group, but is also necessarily higher bandwidth. We invite anyone working on Python-related education projects to join the list. Cordially, Anna Martelli Ravenscroft -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Sat Mar 18 16:14:35 2006 From: peter at engcorp.com (Peter Hansen) Date: Sat, 18 Mar 2006 16:14:35 -0500 Subject: Why won't the sprites in my group show up? (PyGame) In-Reply-To: <1142708325.085786.227620@z34g2000cwc.googlegroups.com> References: <1142708325.085786.227620@z34g2000cwc.googlegroups.com> Message-ID: Isis wrote: > Hi all, > I am writing a snake game, but all is not going well... Chances are good that you'll get access to many more potential respondents by posting the question to the Pygame mailing list. From gh at ghaering.de Wed Mar 15 11:08:33 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 15 Mar 2006 17:08:33 +0100 Subject: Installing PySQLite on OS X 10.4 In-Reply-To: <1142437697.702026.47330@j52g2000cwj.googlegroups.com> References: <1142427211.939368.153850@z34g2000cwc.googlegroups.com> <1142432155.902702.220070@j33g2000cwa.googlegroups.com> <1142437697.702026.47330@j52g2000cwj.googlegroups.com> Message-ID: <44183C01.5060301@ghaering.de> Rob Cowie wrote: > [...] > "build/bdist.darwin-8.5.0-Power_Macintosh/egg/pysqlite2/_sqlite.py", > line 6, in __bootstrap__ > ImportError: > dlopen(/Users/rob/.python-eggs/pysqlite-2.1.3-py2.3-macosx-10.4-ppc.egg-tmp/pysqlite2/_sqlite.so, > 2): Symbol not found: _sqlite3_transfer_bindings > Referenced from: > /Users/rob/.python-eggs/pysqlite-2.1.3-py2.3-macosx-10.4-ppc.egg-tmp/pysqlite2/_sqlite.so > Expected in: dynamic lookup > > I now suspect that this may all be down to the version of sqlite3 > installed as part of OS X 10.4. Some people report success when using > this version with pysqlite, others report failure. Quoting http://initd.org/pub/software/pysqlite/doc/install-source.html """ SQLite: * SQLite version 3.2.2 or later (as of pysqlite 2.1.0). """ You'll need to install a more recent SQLite version than the one shipped with OS X 10.4. Alternatively, you could use pysqlite 2.0.7, which has less cool features, but works with your SQLite version. If you plan to stick to the DB-API and not use convenience features introduced in pysqlite 2.1 it doesn't make any difference. -- Gerhard From techiepundit at futurepundit.com Wed Mar 22 15:10:49 2006 From: techiepundit at futurepundit.com (Randall Parker) Date: 22 Mar 2006 12:10:49 -0800 Subject: Why TypeError: 'str' object is not callable? Message-ID: <1143058248.958219.211950@i40g2000cwc.googlegroups.com> Using Python 2.4.2 on Windows 2000 in SPE. Getting: TypeError: 'str' object is not callable on this line: TmpErrMsg1 = "State machine %s " (StateMachineName) In Winpdb 1.0.6 the StateMachineName is of type str in the Namespace | Local window of local variables. It even has the string value I expect of 'ExampleAO'. That string variable was originally set in another variable by reading a socket packet field. Then it was assigned to StateMachineName. I'm not using str as a variable. I searched all my source code. So why can't I do this? Is there a way to test what "str" is? Maybe importing the minidom messed up what str is? This code used to work. I am trying to figure out what caused it to cease to work. Any ideas? From akameswaran at gmail.com Mon Mar 27 14:34:32 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 27 Mar 2006 11:34:32 -0800 Subject: front end GUI In-Reply-To: <1143479013.659230.91000@j33g2000cwa.googlegroups.com> References: <1143479013.659230.91000@j33g2000cwa.googlegroups.com> Message-ID: <1143488072.507214.14720@i39g2000cwa.googlegroups.com> I have done a few GUI apps in python. I like many started with tKinter. tKinter is quick, easy, ugly and limited. It did really well for little programs I wrote for my wife, like a shopping cart, and some quick admin tools for clients. Now I'm a big wxPython fan. wxPython has a small learning curve if your used to event driven gui programming - but doc can be bad - it's improved majorly for 2.6. The other nice thing, if your users are primarily win32 I've had good success with py2exe(and no my setup files didn't have to be more than about 10-15 lines) and wxPython - so distibution to non-python ppl can be quite good on win32. I've actually had more problems getting tKinter to work with py2exe. However, the suggestions of running this browser based and using a mini python server are good. If your gui requirements are really that simple, a web based approach will have the least headaches in my experience. From cam.ac.uk at mh391.invalid Sun Mar 5 05:57:54 2006 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 05 Mar 2006 10:57:54 +0000 Subject: is there such a built-in funciton, similar to filter In-Reply-To: <1141554823.501805.224790@e56g2000cwe.googlegroups.com> References: <1141554823.501805.224790@e56g2000cwe.googlegroups.com> Message-ID: wcc wrote: > Beginner learning Python here. I know filter(lambda x: x > 3, [1, 2, > 5, -3, 4, 8]) will give me a list [5, 4, 8]. What if I only need to > find the first item in the list that returns Ture when applying the > filter function. In this case, I only want to get the 5, and its index > 2. Is there a built-in function, or function from a module for that? > I think it is not hard to write a function for this. But knowing > Python is "battery included", I thought I'd like to ask. Thanks for > your help. You can use a generator expression like this: >>> items = [1, 2, 5, -3, 4, 8] >>> ((index, item) for index, item in enumerate(items) if item > 3).next() (2, 5) -- Michael Hoffman From smitty_one_each at bigfoot.com Wed Mar 8 05:44:42 2006 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Wed, 08 Mar 2006 05:44:42 -0500 Subject: Learning different languages References: Message-ID: <87mzg16wrp.fsf@bigfoot.com> >>>>> "Rich" == Rich writes: Rich> Hi, Rich> (this is a probably a bit OT here, but comp.lang seems Rich> rather desolated, so I'm not sure I would get an answer Rich> there. And right now I'm in the middle of learning Python Rich> anyway so...) Rich> Anyway, my question is: what experience you people have with Rich> working with different languages at the same time? I think it's akin to speaking multiple human languages. I find, in the web context, that multiple languages help to understand where stuff happens. If it's JavaScript, it's happening in the browser. If it's (other scripting language), it's on the web server. If it's SQL, it's on the database server. I realize that there are other configuration possibilities, e.g. JavaScript on the web server. R, Chris From joel.hedlund at gmail.com Fri Mar 3 06:45:38 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Fri, 03 Mar 2006 12:45:38 +0100 Subject: help in converting perl re to python re In-Reply-To: References: <1141369650.346212.321410@i40g2000cwc.googlegroups.com> Message-ID: > I'd go for > regexp = re.compile(r"<(tag1)>(.*?)") Indeed. I second that. /Joel From frank at chagford.com Tue Mar 21 02:07:27 2006 From: frank at chagford.com (Frank Millman) Date: 20 Mar 2006 23:07:27 -0800 Subject: Pycrypto - active ?? In-Reply-To: <7x7j6ob8ne.fsf@ruckus.brouhaha.com> References: <1142804398.710230.117640@j33g2000cwa.googlegroups.com> <1142807299.141313.306980@i40g2000cwc.googlegroups.com> <1142841321.980154.320340@u72g2000cwu.googlegroups.com> <7xslpdl7yg.fsf@ruckus.brouhaha.com> <1142856119.461122.293150@i40g2000cwc.googlegroups.com> <1142861008.662593.172900@t31g2000cwb.googlegroups.com> <1hchm5b.1vgq264sk3olaN%aleaxit@yahoo.com> <1142919313.863978.133190@i40g2000cwc.googlegroups.com> <7xbqw0bap6.fsf@ruckus.brouhaha.com> <1142921996.314941.175860@j33g2000cwa.googlegroups.com> <7x7j6ob8ne.fsf@ruckus.brouhaha.com> Message-ID: <1142924847.822884.60770@j33g2000cwa.googlegroups.com> Paul Rubin wrote: > "Frank Millman" writes: > > > TLSLite is so far not really a complete SSL implementation by itself. > > > It doesn't know how to properly check the signatures on certificate > > > chains. It has to use an external module like m2crypto for that. > > > > When you say "It has to ...", do you mean that TLSLite will do this > > automatically if m2crypto is installed, or is it up to me to call the > > m2crypto functions to perform this check? > > I don't remember exactly; see the TLSLite docs. I have the vague > memory that you have to specify what kind of checking you want, and if > you say you want the cert chain checked, then TLSLite raises an > exception if the external lib isn't there. But I'm not sure. I seem to have hijacked this thread, which is supposed to be about pycrypto. Sorry about that. I will stop after this one. This is what the docs say - X509CertChain.validate(self,x509TrustList) Check the validity of the certificate chain. This checks that every certificate in the chain validates with the subsequent one, until some certificate validates with (or is identical to) one of the passed-in root certificates. The cryptlib_py module must be installed in order to use this function. I may start looking into this. If I have more questions, I will start a new thread. Thanks for all the assistance. Frank From donald.welch at hp.com Tue Mar 21 14:11:19 2006 From: donald.welch at hp.com (dwelch) Date: Tue, 21 Mar 2006 11:11:19 -0800 Subject: Handling yes/no questions from the User In-Reply-To: <1142961646.431263.290550@t31g2000cwb.googlegroups.com> References: <1142961646.431263.290550@t31g2000cwb.googlegroups.com> Message-ID: <44204fe7$1@usenet01.boi.hp.com> claes_lillieskold at hotmail.com wrote: > I'm writing a scipt that need to interact with the user. > Lets say I have the: > > "Do you want to continue [Y|n]" > > Where just pressing return means Yes (since its uppercase). > > Its easy to write a function for this, but perhaps something like this > already exists. Could someone point me to a class that handles this > kind of user interaction? > > BR / Claes > I think a class would be overkill. I could see making this into a reusable function perhaps. I just use some code like this (with the '*' indicating the default): ok = False while True: user_input = raw_input("\nUse this file (y=yes*, n=no, q=quit) ?").strip().lower() if not user_input or user_input == 'y': ok = True break elif user_input == 'q': print "Exiting." sys.exit(0) elif user_input == 'n': break else: print "Please enter 'y', 'n', or 'q'" -Don From xkenneth at gmail.com Wed Mar 22 13:41:20 2006 From: xkenneth at gmail.com (xkenneth) Date: 22 Mar 2006 10:41:20 -0800 Subject: Conversion from string to integer Message-ID: <1143052880.190153.287940@j33g2000cwa.googlegroups.com> Hi, I've been attempting to write a serial program in python. I talk to a custom designed bit of hardware that sends me back groups that are 2 bytes in length. When i recieve them using either pySerial or USPP i'm not sure how python interprets them. Both of the bytes should be interpreted as one integer. I store each of the two bytes in a python array. Here is an example of the data as printed in a terminal. ['\x1dz', '\xa8<', '\x89{', '}O', 'r\xaf', '\x83\xcd', '\x81\xba', '\x00\x02', '\x00\x00', '\x00\x00', '\x00\x00'] As you can see it either chooses to represent one byte in hex or one in ascii or both in hex etc. I'm just not sure how to get this into an integer format. Thanks for the help. Regards, Ken From robin at NOSPAMreportlab.com Mon Mar 27 18:26:09 2006 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Mon, 27 Mar 2006 23:26:09 +0000 Subject: New-style Python icons In-Reply-To: <95adnfmzFo2dprXZnZ2dneKdnZydnZ2d@comcast.com> References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> <44279790.7020708@jessikat.plus.net> <95adnfmzFo2dprXZnZ2dneKdnZydnZ2d@comcast.com> Message-ID: <44287491.1040502@jessikat.plus.net> Steven Bethard wrote: > Robin Becker wrote: >> Steven Bethard wrote: >> ....... > > Can you see an icon with a blue and yellow plus on your desktop? ;) > > STeVe no -- Robin Becker From martin at v.loewis.de Mon Mar 20 03:31:04 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 20 Mar 2006 09:31:04 +0100 Subject: Python 2.5 Schedule In-Reply-To: References: <1142667600.257048.315910@z34g2000cwc.googlegroups.com> Message-ID: <441e6848$0$21786$9b622d9e@news.freenet.de> Ben Finney wrote: >> - ASCII is the default coding > > Er? How did this happen? > > To be specific, what about all the movement toward UTF-8? See PEP 263. ASCII is the default encoding for source code; if you want to use UTF-8 in source code, either put # -*- coding: utf-8 -*- into the file, or start the file with the UTF-8 signature (if your editor supports that). Regards, Martin From onurb at xiludom.gro Wed Mar 22 07:44:42 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 22 Mar 2006 13:44:42 +0100 Subject: py web-app-frameworks without a rdbms... In-Reply-To: <1142989572.483475.158570@e56g2000cwe.googlegroups.com> References: <1142989572.483475.158570@e56g2000cwe.googlegroups.com> Message-ID: <442146f5$0$7086$626a54ce@news.free.fr> venkatbo at yahoo.com wrote: > Hi folks, > > Of TurboGers & Django WAF candidates, which one would be easier to use > in an environment where the data/content doesn't come an RDBMS, but > from other server-side apps... IMHO, both. > If these are not good candidates, could > you suggest appropriate ones... Well... There are *many* web frameworks in Python, you know ? -- 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 Fri Mar 3 10:42:30 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 3 Mar 2006 07:42:30 -0800 Subject: setattr question References: <1141318090.569997.247760@z34g2000cwc.googlegroups.com> <4407355d$0$10756$636a55ce@news.free.fr> <1141335149.855403.261510@e56g2000cwe.googlegroups.com> <440803ba$0$15069$636a55ce@news.free.fr> <1141382590.464384.29840@v46g2000cwv.googlegroups.com> <44084be0$0$15822$636a55ce@news.free.fr> Message-ID: <1141400550.229176.35510@v46g2000cwv.googlegroups.com> bruno at modulix wrote: > Gerard Flanagan wrote: > > The functions were kind of related > > and meaningless outside the module they were declared - > > FWIW (and from the snippet I saw), these functions are useless even in > the module !-) > ok, ok... :-) > Unless you want to dynamically choose the concrete class at runtime > based on platform/settings/phase of the moon/whatnot (which seems not to > be te case in the snippet you posted), you don't need these functions, > just instanciating the concrete class is enough. Remember that Python > classes *are* factory already - and that you can freely replace a class > by any callable returning an instance, ie: > > == before refactoring, directly instanciating concrete class == > # myhtmlmodule.py > class HtmlElement(tag, *args, **kw): > # code here > > # myclientmodule.py > from myhtmlmodule import HtmlElement > ul = HtmlElement('ul') > > > == after refactoring, using a factory function == > # myhtmlmodule.py > class _HtmlElement1(tag, *args, **kw): > # code here > > class _HtmlElement2(tag, *args, **kw): > # other code here > > # yes, it's now a function... > def HtmlElement(tag, *args, **kw): > if phase_of_the_moon(): > klass = _HtmlElement1 > else: > klass = _HtmlElement2 > return klass(tag, *args, **kw) > > # myclientmodule.py > # well... nothing changed here !-) > from myhtmlmodule import HtmlElement > ul = HtmlElement('ul') > ah, I'm getting it. > > > I've ditched the factory class in any case: > > > > http://gflanagan.net/site/python/htmlbuilder/HtmlBuilder.py > > (FWIW) > > Seems mostly clean. May I suggest a couple small corrections/improvements ? > > 1/ potential bugfix: > try: > from tidy import parseString > except ImportError: > def parseString(text): > # woops, this function is supposed to return something > #pass > return text > > 2/ safer and cleaner > class HtmlPage(HtmlElement): > # removed class vars, > # replaced with default in __init__ > def __init__(self, title, **kw): > self.title = title > self.stylesheets = kw.get('stylesheets', []) > self.doctype = kw.get('doctype', HTML4_STRICT) > That's much better - thanks very much for taking the time, I'm a little bit wiser! regards Gerard > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From "derek\" at (none) Wed Mar 1 13:20:50 2006 From: "derek\" at (none) (none) Date: Thu, 02 Mar 2006 02:20:50 +0800 Subject: looking for help about python-sane In-Reply-To: <1141223894.751643.32240@u72g2000cwu.googlegroups.com> References: <1141223894.751643.32240@u72g2000cwu.googlegroups.com> Message-ID: <4405e609$1@127.0.0.1> JW wrote: > Every time, or just this run? > every time From rcs at bgoark.no Fri Mar 24 19:15:57 2006 From: rcs at bgoark.no (baalbek) Date: Sat, 25 Mar 2006 01:15:57 +0100 Subject: C-API: A beginner's problem In-Reply-To: References: Message-ID: <44248c0c$0$22978$c83e3ef6@nn1-read.tele2.net> Fabian Steiner wrote: > What do I have to change in order to make the code work? I'm afraid to say: your knowledge of C :-) But don't worry, C is an easy language to learn, and a very valuable skill to have. Baalbek From ruby at no.spam Thu Mar 9 22:06:26 2006 From: ruby at no.spam (Michal Kwiatkowski) Date: Fri, 10 Mar 2006 04:06:26 +0100 Subject: Why property works only for objects? Message-ID: Hi, Code below shows that property() works only if you use it within a class. ------------------------------------------------ class A(object): pass a = A() a.y = 7 def method_get(self): return self.y a.x = property(method_get) print a.x # => A.x = property(method_get) print a.x # => 7 ------------------------------------------------ Is there any method of making descriptors on per-object basis? I would like to customize x access in different objects of class A. Is this possible and how? 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 lucaberto at libero.it Fri Mar 31 11:00:47 2006 From: lucaberto at libero.it (luca72) Date: 31 Mar 2006 08:00:47 -0800 Subject: wx.checklistbox In-Reply-To: <1143817821.621038.205640@g10g2000cwb.googlegroups.com> References: <1143815725.730867.324970@j33g2000cwa.googlegroups.com> <1143817821.621038.205640@g10g2000cwb.googlegroups.com> Message-ID: <1143820847.823668.90720@j33g2000cwa.googlegroups.com> I have solved with appen.items() Regards Luca From danbrwn at gmail.com Mon Mar 27 09:22:12 2006 From: danbrwn at gmail.com (Dan) Date: 27 Mar 2006 06:22:12 -0800 Subject: COM Client / Server creation? In-Reply-To: References: <1143060785.381056.208660@g10g2000cwb.googlegroups.com> <1143061924.070461.72060@t31g2000cwb.googlegroups.com> <87ek0urn3v.fsf@pobox.com> Message-ID: <1143469332.515027.322530@i40g2000cwc.googlegroups.com> Thanks, I am going to try to implement with Python. From muttu2244 at yahoo.com Tue Mar 28 04:43:32 2006 From: muttu2244 at yahoo.com (muttu2244 at yahoo.com) Date: 28 Mar 2006 01:43:32 -0800 Subject: To run a python script in all the machines from one server Message-ID: <1143539012.363882.74740@j33g2000cwa.googlegroups.com> Hi Everyone I want to run a python script in all the machines that are connected through local network and collect the information about that machine such as HDD size, RAM capacity(with number of slots) ,processer speed etc. But i want to run a script from just the server, so that it should start scripts in all other machines, and get their local machines information and dump the same information in some FTP. Could you please let me know how can i do this?? Thanks Yogi From vincenzo.cacciatore at gmail.com Wed Mar 15 08:18:23 2006 From: vincenzo.cacciatore at gmail.com (LabWINC) Date: 15 Mar 2006 05:18:23 -0800 Subject: FIR filtering Message-ID: <1142428703.224948.317700@u72g2000cwu.googlegroups.com> Hi all, i'm looking for a module to implement a digital FIR filter! Can anyone help me? Thanks, Vincent From gene.tani at gmail.com Tue Mar 7 09:12:59 2006 From: gene.tani at gmail.com (gene tani) Date: 7 Mar 2006 06:12:59 -0800 Subject: Checking function calls In-Reply-To: References: Message-ID: <1141740779.630548.135960@e56g2000cwe.googlegroups.com> Roy Smith wrote: > Fredrik Tolf wrote: > >If I have a variable which points to a function, can I check if certain > >argument list matches what the function wants before or when calling it? > > > >Currently, I'm trying to catch a TypeError when calling the function > >(since that is what is raised when trying to call it with an illegal > >list), but that has the rather undesirable side effect of also catching > >any TypeErrors raised inside the function. Is there a way to avoid that? > > The only way is to read the documentation for the function (or, the > source code). > > Can you be a little more specific about what you're trying to do? Can > you post your code? if you know ahead of runtime which methods are at issue and what method signatures you want, multimethod decorators, maybe? http://www.artima.com/weblogs/viewpost.jsp?thread=101605 (read comments: PJE, ian bicking or you can arg-test inside the method, which isn't much fun http://www.python.org/doc/faq/programming.html#how-can-i-overload-constructors-or-methods-in-python From python.list at tim.thechases.com Fri Mar 24 12:04:09 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 24 Mar 2006 11:04:09 -0600 Subject: What's The Best Editor for python In-Reply-To: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> References: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> Message-ID: <44242689.70905@tim.thechases.com> > Can one of you say to me what's the best editor for > editing the python programs ( for linux or windows ), and > if you can send it to me to the adresse Hmmm...it's been almost a week since this topic came up on the list. Good to see the topic is undead :) For plenty of reading, check out the list archives: http://groups.google.com/group/comp.lang.python/search?group=comp.lang.python&q=editor+%28best+OR+perfect+OR+ideal%29 Pretty much any text editor will do. If you're developing on both Linux and Windows, it's an advantage to have an editor that you can use on both. I happen to use vim/vi which is available pretty much wherever you go. About the same sorta thing can be said for emacs, though I'm not a user, so I can't comment on it. I'll grant that vi/vim has a learning curve like a brick wall, but once you're over the initial learning hurdle, it reaps heaps of rewards. Check out http://www.python.org/moin/PythonEditors Try 'em out and see what *you* like. In a pinch, there's always ed: http://www.gnu.org/jokes/ed.msg.html http://www.gnu.org/software/ed/ed.html Or edlin if you're on Dos/Win32 :) Though I think in such an event on Dos/Win32, I'd almost rather use "copy con" as my editor... -tkc From dongdonglove8 at hotmail.com Wed Mar 8 01:08:21 2006 From: dongdonglove8 at hotmail.com (dongdong) Date: 7 Mar 2006 22:08:21 -0800 Subject: how to download a zip or rar file to local machine using python? In-Reply-To: <1141797709.923751.50230@j52g2000cwj.googlegroups.com> References: <1141795347.072982.216900@j52g2000cwj.googlegroups.com> <1141797709.923751.50230@j52g2000cwj.googlegroups.com> Message-ID: <1141798101.698272.61370@u72g2000cwu.googlegroups.com> but I want to ask: how to find out explaination about the parameters of 'open()' function? From aahz at pythoncraft.com Thu Mar 23 15:54:53 2006 From: aahz at pythoncraft.com (Aahz) Date: 23 Mar 2006 12:54:53 -0800 Subject: python-announce moderation (was: Re: ANN: ClientForm 0.2.2 released) References: Message-ID: In article , John J. Lee wrote: >aahz at pythoncraft.com (Aahz) writes: >> In article , >> John J Lee wrote: >>> >>>Hmm, hschilling at nasa.gov, who are you? python-announce moderator? I >>>didn't put you on my To: line (nor python-list for that matter, but I >>>guess that's a reasonable place for it to go...). >>> >>>Also FYI, it ended up going to wwwsearch-general twice, I guess because >>>the you (or the moderation software) forwarded it there after moderation, >>>which isn't really necessary. >> >> Huh??? > >Sorry. I forgot my reply wouldn't include the headers (should have >hit 'forward' instead of 'reply'. > >I sent the message I quoted "To: python-announce at python.org, >wwwsearch-general at lists.sourceforge.net". It arrived at the latter >list. A while later, it got moderated for python-announce, and was >sent out like so: > >Date: Thu, 23 Mar 2006 18:25:57 +0000 (GMT Standard Time) >From: John J Lee >To: hschilling at nasa.gov >Cc: wwwsearch-general at lists.sourceforge.net, python-list at python.org >Subject: [wwwsearch-general] python-announce moderation (was: Re: ANN: ClientForm 0.2.2 > released) > >I wondered where that To: line came from (I don't even know who >hschilling at nasa.gov is), and why it was sent to wwwsearch-general >again (there was no need, since my original To: line already got it to >that list). Hmmmm.... hschilling is NOT one of the python-announce moderators, so zir e-mail setup is probably b0rken, accounting for all the problems you mentioned. I frequently send e-mail to python-announce, python-list, and baypiggies with no problems. It's possible that the wwwsearch list is malfunctioning if hschilling is one of the moderators for that list. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From larry.bates at websafe.com Thu Mar 23 16:31:06 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 23 Mar 2006 15:31:06 -0600 Subject: Remove integer from float number In-Reply-To: <4422fcac@news.eftel.com> References: <1143142664.507941.130240@g10g2000cwb.googlegroups.com> <4422FAA9.50506@websafe.com> <4422fcac@news.eftel.com> Message-ID: John Machin wrote: > On 24/03/2006 6:44 AM, Larry Bates wrote: >> Derek Basch wrote: >> >>> How can I return: >>> >>> ".666" >>> >>> from float: >>> >>> "0.666" >>> >>> This is what I have so far: >>> >>> >>>>>> "%.6f" % x >>> >>> Thanks Everyone, >>> Derek Basch >>> >> >> >> This works but I'm not entirely sure I know what you are >> trying to accomplish. >> >> ("%.3f" % x)[1:] >> > >>>> x = 12345.666; ("%.3f" % x)[1:] > '2345.666' >>>> > > I'm sure of neither what the OP is trying to accomplish nor what Larry's > definition of "works" is :-) > > Perhaps the condition abs(x) < 1.0 is implied ... For the example given, my code works. With so little information the only thing I could do is answer the specific question and caveat it that I don't know "exactly" what OP is trying to accomplish. By the OPs response to my post, it was what he was looking for. But I agree it is very much an edge-case question. -Larry Bates From amk at amk.ca Tue Mar 14 09:43:19 2006 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 14 Mar 2006 08:43:19 -0600 Subject: Cheese Shop: some history for the new-comers References: <44126523$0$1016$afc38c87@news.optusnet.com.au> Message-ID: On Sun, 12 Mar 2006 10:25:19 +0100, Fredrik Lundh wrote: > and while you're at it, change "python-dev" to "developers" and > "psf" to "foundation" (or use a title on that link). I've changed the PSF link, but am not sure what to do about the python-dev link. As others have noted, "Developers" is ambiguous about whether it's for people who develop in Python or who develop Python itself. "Core Development"? (Used on both perl.org and tcl.tk, so maybe this is the best option.) "Development Team"? --amk From onurb at xiludom.gro Tue Mar 28 03:06:00 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 28 Mar 2006 10:06:00 +0200 Subject: How to inplement Session in CGI In-Reply-To: <1143525508.503801.54770@i39g2000cwa.googlegroups.com> References: <1143525508.503801.54770@i39g2000cwa.googlegroups.com> Message-ID: <4428eea8$0$27048$626a54ce@news.free.fr> Sullivan WxPyQtKinter wrote: > Python disappointly failed to provide a convinient cgi session > management module. Probably because there are much better options for web programming in Python ? > Not willing to use external modules, I would like to > implement a simplest Session object on my own. > > The basic problem is: how could a python CGI program understand several > requests are in the same session? Just like anyone else: by setting a session cookie. This is not related to CGI, it's just how HTTP works. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From trepca at gmail.com Fri Mar 24 06:21:28 2006 From: trepca at gmail.com (Sebastjan Trepca) Date: Fri, 24 Mar 2006 12:21:28 +0100 Subject: imap folder scanner In-Reply-To: References: Message-ID: A very simple example... import imaplib m = imap.IMAP4() m.login(username,password) m.select('myfolder') status, data = m.search(None,'(SUBJECT "BIKES")') assert status=='OK', "Error. Message: %s"%data data = data[0] #you get your results in a list and search returns only one result assert data,"No results" #cool, we have results, but IMAP's search command only returns IDs so we have to fetch #msgs now status,senders = m.fetch(data.replace(' ',','),'(BODY.PEEK[HEADER.FIELDS (FROM)])') assert status=='OK', "Error. Message: %s"%data Now you just have to parse the "senders" data. There are many examples about sending emails with python, like this one: def send_notice(): import smtplib msg = 'we got your mail, indeed' from email.MIMEText import MIMEText mail = MIMEText(msg, 'plain', 'utf-8') mail['From'] =fro='from at example.com' mail['Subject'] = "Spam machine" mail['To'] = to = 'to at example.com' server = smtplib.SMTP('localhost') errors = server.sendmail(fro, to, mail.as_string()) server.quit() That other program should be very simple to make now. Sebastjan On 3/24/06, Kun wrote: > Hey guys, I would like to have a code in python (as simple as possible) > to scan a specific folder in my mailbox and if the subject is equal to, > say, 'BIKES', I would like to have the code automatically send the > SENDER an email saying something like "We have received your Email". > Furthermore, I would also like to somehow save the sender's email into a > list which would be compiled by another python program into an html file > that would show a list of email addresses whose subject matched 'BIKE' > > I know i am asking for a lot but since i am new to python, can someone > help me out with this? Whether its tips or code, i'll be very excited to > hear your answer. Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > From daniel.dittmar at sap.corp Wed Mar 15 08:21:16 2006 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Wed, 15 Mar 2006 14:21:16 +0100 Subject: global, globals(), _global ? In-Reply-To: References: Message-ID: Roy Smith wrote: > In article , > robert wrote: > >> Using global variables in Python often raises chaos. Other languages use >> a clear prefix for globals. > > Unsing globals raises chaos in any language. They should be shunned and > avoided. Solution: replace globals with Singletons ;-) Daniel From MidiBot at gmail.com Sun Mar 19 19:36:27 2006 From: MidiBot at gmail.com (MidiBot at gmail.com) Date: 19 Mar 2006 16:36:27 -0800 Subject: System Information Message-ID: <1142814987.299021.7380@i39g2000cwa.googlegroups.com> Hello. I want to write a program in which the main functionality will depend on whether or not my computer is connected to a power adapter(this is for laptops). I looked in the online-documentation for this and had no luck. I imagine it is quite easy and may even be as simple as a boolean variable...? All I want to be able to tell is whether or not my computer is being externally powered. More specifically I want to be able to have my program running, and be alerted if I un-plug my power adapter. I am using a Mac(powerbook) with if that makes any difference. Thank you very much. From scott.daniels at acm.org Mon Mar 13 11:53:51 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 13 Mar 2006 08:53:51 -0800 Subject: Please, I Have A Question before I get started In-Reply-To: <40l912h0aubfgai2en7n465ml9olg746h9@4ax.com> References: <40l912h0aubfgai2en7n465ml9olg746h9@4ax.com> Message-ID: <4415a17d$1@nntp0.pdx.net> Skipper wrote: > ... I am not asking for anyone to do this for me I simply want to > know if I can do what I need to do with Python .... > Can python do this? I realize I am responsible for the menu sets, > pictures .... attaching sounds etc .... As you have been told by many other respondents above, the task is not as simple as it seems it should be. If you decide to go ahead and attempt it in Python (after you have learned some easier stuff), you will definitely get lots of assistance here. You just need to decide which mountains you want to climb, and which ones you pass up. --Scott David Daniels scott.daniels at acm.org From dinko.tenev at gmail.com Fri Mar 17 11:16:10 2006 From: dinko.tenev at gmail.com (Dinko Tenev) Date: 17 Mar 2006 08:16:10 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1142589945.078364.32870@i39g2000cwa.googlegroups.com> <1142599685.186209.177630@j33g2000cwa.googlegroups.com> Message-ID: <1142612170.404220.23410@e56g2000cwe.googlegroups.com> wkehowski at cox.net wrote: > It would seem that your program is just filtering the full cartesian > product, right? The solution I'm looking for generates the elements > one-by-one so that it could be used in a loop. Oops...missed that part. It took me a while to study the exchange on this topic more thoroughly, and I now fully appreciate the fact that the problem calls for a much more sophisticated approach. Sorry for the hasty shot, I'll give it another shortly. Cheers, Dinko From zhan0645 at yahoo.com Wed Mar 29 19:50:40 2006 From: zhan0645 at yahoo.com (Yanping Zhang) Date: Wed, 29 Mar 2006 16:50:40 -0800 (PST) Subject: Updated: python ctype question about "access violation reading location 0x5a5a5a5a" Message-ID: <20060330005040.8340.qmail@web52914.mail.yahoo.com> Here are more details about my codes, please help! The function declared in C: typedef void (WINAPI *PLEARNCALLBACKPROC) (unsigned int progress, unsigned int sigQuality, unsigned long carrierFreq, void *userData); UUIRTDRV_API BOOL PASCAL UUIRTLearnIR(HUUHANDLE hHandle, int codeFormat, char *IRCode, PLEARNCALLBACKPROC progressProc, void *userData, BOOL *pAbort, unsigned int param1, void *reserved0, void *reserved1); My python codes: import ctypes port = windll.uuirtdrv myhandle = c_void_p() myhandle = port.UUIRTOpen() #+++++++ Call back function ++++++++ LEARNCALLBACKFUNC = CFUNCTYPE(c_void_p, c_uint, c_uint, c_ulong, c_void_p) def py_learncallback_func(progress,sigQuality, carrierFreq, userdata): print "progress is: %d %d %d %d" % (progress, sigQuality & 0xff, carrierFreq, userdata) if progress == 100: mybool = c_int(1) return callback_func = LEARNCALLBACKFUNC(py_learncallback_func) #++++++++++++++++++++++++++++++++++++++ glearnBuffer = create_string_buffer('\000'*2048) mybool = c_int(0) param1 = c_int(0) reserved0 = c_void_p(0) reserved1 = c_void_p(0) mydata = create_string_buffer("0x5a5a5a5a") #userdata = c_long(0x5a5a5a5a) #failed #userdata = byref(mydata) #failed #userdata = pointer(mydata) #failed userdata = c_void_p(0x5a5a5a5a) #failed learnformat = c_int(0x0000) port.UUIRTLearnIR(myhandle, learnformat, glearnBuffer, callback_func, userdata, mybool,param1,reserved0, reserved1) I tried to define userdata in different ways and all failed with "access violation reading(writing) location...". The c routine just passes userdata to call back function and didn't use it anywhere else. Thanks! > Hi All, > > I need to use this C routine in python and there is a void pointer parameter in it: > (this routine was written by someone else): > > myfunc(int a, (void *)userdata, int b) > > I saw someone in his C++ wrapper used this routine in this way: > myfunc(a, (void *)0x5a5a5a5a, b) > > In my python wrapper, I tried to call it as the following and both failed: > 1. myfunc(c_int(a), 0x5a5a5a5a, c_int(b)) > got error "access voilation reading from 0x5a5a5a5a" > 2. > data = 0x5a5a5a5a > mydata = c_void_p(data) > myfunc(c_int(a), mydata, c_int(b)) > same error as in 1 > > Can anyone know how to fix it? Thanks! > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From http Tue Mar 28 14:30:05 2006 From: http (Paul Rubin) Date: 28 Mar 2006 11:30:05 -0800 Subject: No Cookie: how to implement session? References: <1143567624.164865.71730@v46g2000cwv.googlegroups.com> <9uvi225dlg8kd892jpfg8mqne6chnavus6@4ax.com> Message-ID: <7xbqvqnz9e.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > Yes... And watch them flounder on sites that use cookies /for/ a > form of security (ie, those sites that require logins...) Cookies can be > set to expire, so the "session" can time-out... whereas... Sites should never rely on cookies timing out. If there's any security concern about session persistence and you don't want to track the session timeout on the server, then encode an expiration time into the cookie itself, and cryptographically authenticate the cookie. > > I tried to add hidden field with a sessionID in every python CGI script > > generated web pages, so everytime my client POST a request, the server The trouble here is that it stops internal links (retrieved with GET rather than POST) from working. So normally what you're describing is done with session ID's in the url (see amazon.com for example). That, too, isn't so great for security, especially for ecommerce sites, since people tend to share url's with their friends. E.g., they'll post to Usenet or web bbs's, So-and-so is offering a great deal on Python manuals, the url is where "whatever" includes the session ID. Anyone clicking the url then ends up with the same shopping cart as the person who posted it. To OP: keep in mind also that anyone who disables cookies probably also disables javascript, so relying on javascript as you described for redirection doesn't work too well either. From johnjsal at NOSPAMgmail.com Mon Mar 20 16:34:08 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 20 Mar 2006 21:34:08 GMT Subject: what's the general way of separating classes? In-Reply-To: <1142889430.140332.318040@z34g2000cwc.googlegroups.com> References: <1142889430.140332.318040@z34g2000cwc.googlegroups.com> Message-ID: I V wrote: > Now, in your code you can do: > > import package > > c = package.C1() > > If you hadn't included the lines in __init__.py, you would have to > write: > > import package > > c = package.class1.C1() > Ah, this makes sense! Thanks! :) From steve at holdenweb.com Mon Mar 20 05:08:43 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 20 Mar 2006 10:08:43 +0000 Subject: Keeping a function from taking to long--threads? In-Reply-To: <001601c64bbb$cae3c490$6700a8c0@D1FWTS61> References: <001601c64bbb$cae3c490$6700a8c0@D1FWTS61> Message-ID: brandon.mcginty at gmail.com wrote: > Thanks, however, I forgot to mention that I'm using windows, and from what > I've tried, the setdefaulttimeout function doesn't work on my machine. > Again, thanks for your help! > Brandon McGinty > What version of Python are you running? Under 3.4 setdefaulttimeout() works perfectly well on my Windows system. If you are running 2.3 or earlier, you may want to use Timothy O'Malley's timeoutsocket module instead. However, you seem to be assuming that socket.gethostbyaddr() will report on the existence of systems, which I don't think it will - that function is for converting IP addresses to names: >>> import socket >>> socket.gethostbyaddr("127.0.0.1") ('localhost', [], ['127.0.0.1']) >>> socket.gethostbyaddr("192.168.10.215") ('bigboy.lan', [], ['192.168.10.215']) >>> socket.gethostbyaddr("82.165.194.52") ('perfora.net', [], ['82.165.194.52']) >>> So it will tell you something about the DNS service's content rather than the existence or non-existence of systems at a particular IP address. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From ravi.annaswamy at gmail.com Fri Mar 31 00:53:17 2006 From: ravi.annaswamy at gmail.com (ravi.annaswamy at gmail.com) Date: 30 Mar 2006 21:53:17 -0800 Subject: How to debug python code? References: <1143782330.199836.221880@v46g2000cwv.googlegroups.com> Message-ID: <1143784397.058216.230490@i40g2000cwc.googlegroups.com> Here is an outstandingly well written article, with examples, from Stephen Ferg: http://www.ferg.org/papers/debugging_in_python.html Ravi From michaeltaft at gmail.com Sat Mar 11 18:26:53 2006 From: michaeltaft at gmail.com (mwt) Date: 11 Mar 2006 15:26:53 -0800 Subject: Help Create Good Data Model In-Reply-To: <1142115988.067193.239570@i39g2000cwa.googlegroups.com> References: <1142107183.358685.266440@i39g2000cwa.googlegroups.com> <1142115988.067193.239570@i39g2000cwa.googlegroups.com> Message-ID: <1142119613.829337.84970@p10g2000cwp.googlegroups.com> Well, thank the gods for unit testing. Here's the fah_data module with fewer errors: import copy, threading, observable class FAHData(observable.Observable): """The data model for the F at H monitor.""" def __init__(self): observable.Observable.__init__(self) self.data = {}#this dict will hold all data self.mutex = threading.RLock() def get_all_data(self): """Returns a COPY of entire data dict.""" #not sure deepcopy() is really necessary here #but using it for now #might cause some weird synchronization problems... try: self.mutex.acquire() return copy.deepcopy(self.data) finally: self.mutex.release() def get_data(self, key): """Returns a COPY of data element.""" try: self.mutex.acquire() return copy.deepcopy(self.data[key]) finally: self.mutex.release() #these three methods don't need a mutex because they are atomic (I think): #--------------------------------------------> def set_value(self, key, value): """Sets value of data element.""" self.data[key] = value observable.Observable.notifyObservers(self, arg = 'ELEMENT_CHANGED') def set_data(self, data): """Sets entire data dictionary.""" self.data = data observable.Observable.notifyObservers(self, arg = 'DATA_CHANGED') def clear_data(self): """Clears entire data dictionary.""" self.data = {} observable.Observable.notifyObservers(self, arg = 'DATA_CHANGED') #<--------------------------------------------- From larry.bates at websafe.com Tue Mar 14 18:07:39 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 14 Mar 2006 17:07:39 -0600 Subject: Python Debugger / IDE ?? In-Reply-To: <1142357338.313046.139060@i39g2000cwa.googlegroups.com> References: <1142357338.313046.139060@i39g2000cwa.googlegroups.com> Message-ID: krypto.wizard at gmail.com wrote: > Is there any editor or IDE in Python (either Windows or Linux) which > has very good debugging facilites like MS VisualStudio has or something > like that. > > I like SPE but couldn't easily use winPDP. I need tips to debug my code > easily. > > Every help is greatly appreciated. > > Thanks > I've found that using logging works well for me. I put statements in my program that log information, trace, intermediate results, ..., and wrap them in trace/debug if statements. Higher values of debug get more "stuff" logged. Then I leave everything in the program. When something goes wrong, run it with debug level and I can figure out what is happening. This is especially good when problem pops up 2 years from now. I just have client run with debug=4 and I look at the logfile. If you get in a habit of writing ALL your software this way, you find that it is quite powerful and easy. I haven't found the overhead of all the if statements to be anything to worry about. You can use the standard library logging module (I wrote my own before it was available and I've never changed to the one in the standard library). -Larry Bates From johnpote at blueyonder.co.uk Fri Mar 17 20:23:09 2006 From: johnpote at blueyonder.co.uk (John Pote) Date: Sat, 18 Mar 2006 01:23:09 GMT Subject: Python Evangelism References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> <8ba244fb0603091140n2e22494by8c91af6f638c80c1@mail.gmail.com> Message-ID: <1iJSf.204985$YJ4.95005@fe2.news.blueyonder.co.uk> If I get time I'll expand my thoughts and experiences but for now, Don't know what Ruby on Rails is but it's catchy and current high volume of interest makes me think - I should look into it. Django, skip reading this thread before and I had not even picked up it was a Python product (still don't know what it is too little time to look!) Python seems to concentrate on language development rather than environment development. Programmer productivity depends much more on the associated environment - docs, code editor, libraries, wysiwyg GUI designer - than the language. So far my experience is that the further away from the core language the worst things get. My principle moan about the standard library is lack of formal stating of ALL exceptions that can be thrown by a module. Sometimes the detail is burried in the general text about the module which makes it difficult to eye ball quickly. httplib does not mention any of the socket module exceptions that can be thrown. This makes it difficult to write stable bullet proof code. Finding myself slowed down too much by hand coding tkinter (and modifying it weeks later) I've switched to wxPython and Glade. Certainly better but wxPython docs are not ideal. (only reason for switching is lack of wysiwyg GUI designer for it) I get a myApp.pyw working on one machine. Copy to another and maybe forget something (usually updating my own python library so a header import fails) and what happens? nothing if tkinter has not yet fired up the gui. and even if it has and there's an uncaught exception the app just closes. Any error message and traceback are dumped because there's no dos box. On the positive side Twisted (I have the docs and book) looks exactly what I need in all respects. I think the language has already made Python, the rest is down to its 'environment'. Best wishes to everyone, John Pote "Douglas Alan" wrote in message news:m2wtesen95.fsf at lexx.mit.edu... > Andrew Gwozdziewycz writes: > >> Douglas Alan wrote: > >>> Ruby didn't start catching on until Ruby on Rails came out. If >>> Python has a naming problem, it's with the name of Django, rather >>> than Python. Firstly, Django doesn't have "Python" in the name, so >>> it doesn't popularize the language behind it, even should Django >>> become very popular. Secondly, Django just doesn't have the ring >>> of "Ruby on Rails". > >> I'll admit "Ruby on Rails" is a clever name. The fact that you >> mention it "didn't catch on" is only partially true. > > I'm sorry if I wasn't clear. By "didn't catch on", I only meant that > it had little mainstream success. At least in the US. I'm certainly > aware that it has had a significant community of devotees for some > time now. > >> Rails did however jump start it's new career as the definitive >> web2.0 language, but who cares? Not me! > > Well, I'm not sure that the threat to Python is being fully > appreciated here. I have friends who are fully convinced that Python > is doomed because Ruby has all the buzz now. I think that their > predictions of doom and gloom for Python are overstated. For one > thing, I point out to them that Rails is what really has all the buzz, > not Ruby per se. But such subtle distinctions seem to often get lost > in the type of buzz that causes technologies to succeed or fail. This > is an example of how names are indeed very important. > > There *is* a serious worry here. For instance, look how PHP > completely decimated Perl in its biggest market niche at the time (CGI > programming) in just a couple of years. PHP couldn't use that > advantage to threaten the more general scripting niches, but unlike > PHP, Ruby might certainly be able to leverage that advantage, as it is > also a perfectly good general-purpose programming language. Ruby's > domain is not limited to just server-side web scripting. > > For those who don't believe that Ruby on Rails does have an incredible > amount of buzz going for it right now, I do have a number of personal > data points that seem to indicate that it is indeed undergoing > exponential growth at the moment: (1) I'm sitting in on a class at MIT > on developing web applications. For their projects and assignments, > the students are allowed to chose whatever programming languages, > databases (as long as they are ACID-compliant), and development > environments that they prefer. From what I can tell, more than half > of the class is using Ruby on Rails. One group is using C# and .NET. > Another is using JSP. No one is using PHP. No one is using Django. > One group was doing straight Python CGI, but I think they switched to > Rails. (2) I've started to see advertisements for web hosting > services where the ads say, "PHP! MySQL! Rails!". (3) I have > friends who work in companies that are big Python shops, but they seem > to be moving to Rails for web development. > >> Hell I like django quite a bit, but anyone writing something for >> django knows it's written in python. > > Yes, and for Rails, everyone who has never even seen a single line of > Ruby code knows that it is Ruby-based. The same cannot be said for > Django. > >> If some non-programmer decided to create a new web app, and his >> friend said, 'I hear django is quick and oh, it use's this really >> cool easy to learn language python,' What's the difference? > > There's a huge difference. Ruby on Rails gives Ruby great brand > recognition, while Django does nothing at all for Python's brand > recognition. Just pay attention to TV commercials: a large fraction > of them have nothing to say whatsoever about the merits of their > product -- the ads just want to get the brand name into your head. > For better or worse, this is how human psychology works. > > In any case, it's almost certainly too late for Django to achieve the > kind of popularity that Rails is achieving; if you Google > "web-development rails", you get 3 million hits, while if you Google > "web-development django", you get 82,000 hits. So, unfortunately, how > to best use Django to help popularize Python is almost certainly moot > at this point. > > |>oug From ziga.seilnacht at gmail.com Sat Mar 18 17:25:01 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 18 Mar 2006 14:25:01 -0800 Subject: __dict__ strangeness In-Reply-To: <482lr6Fhs1jvU1@individual.net> References: <482lr6Fhs1jvU1@individual.net> Message-ID: <1142720701.178447.71620@i40g2000cwc.googlegroups.com> Georg Brandl wrote: > Hi, > > can someone please tell me that this is correct and why: > > >>> class C(object): > ... pass > ... > >>> c = C() > >>> c.a = 1 > >>> c.__dict__ > {'a': 1} > >>> c.__dict__ = {} > >>> c.a > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'C' object has no attribute 'a' > >>> > >>> class D(object): > ... __dict__ = {} > ... > >>> d = D() > >>> d.a = 1 > >>> d.__dict__ > {} > >>> d.__dict__ = {} > >>> d.a > 1 > > Thanks, > Georg Here is another example that might help: >>> class E(object): ... __dict__ = {'a': 1} ... >>> e = E() >>> e.__dict__ {'a': 1} >>> E.__dict__ >>> E.__dict__['a'] Traceback (most recent call last): File "", line 1, in ? KeyError: 'a' >>> E.__dict__['__dict__'] {'a': 1} Ziga From aaronwmail-usenet at yahoo.com Wed Mar 8 09:22:19 2006 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 8 Mar 2006 06:22:19 -0800 Subject: recycling internationalized garbage Message-ID: <1141827739.823228.198160@j33g2000cwa.googlegroups.com> Hi folks, Please help me with international string issues: I put together an AJAX discography search engine http://www.xfeedme.com/discs/discography.html using data from the FreeDB music database http://www.freedb.org/ Unfortunately FreeDB has a lot of junk in it, including randomly mixed character encodings for international strings. As an expediency I decided to just delete all characters that weren't ascii, so I could get the thing running. Now I look through the log files and notice that a certain category of user immediatly homes in on this and finds it amusing to see how badly I've mangled the strings :(. I presume they chuckle and make disparaging remarks about "united states of ascii" and then leave never to return. Question: what is a good strategy for taking an 8bit string of unknown encoding and recovering the largest amount of reasonable information from it (translated to utf8 if needed)? The string might be in any of the myriad encodings that predate unicode. Has anyone done this in Python already? The output must be clean utf8 suitable for arbitrary xml parsers. Thanks, -- Aaron Watters === As someone once remarked to Schubert "take me to your leider" (sorry about that). -- Tom Lehrer From danbrwn at gmail.com Thu Mar 23 16:13:47 2006 From: danbrwn at gmail.com (Dan) Date: 23 Mar 2006 13:13:47 -0800 Subject: COM callbacks in Python Message-ID: <1143148427.605756.205120@g10g2000cwb.googlegroups.com> I need to register for a COM callback under Windows. I am using an ADO recordset interface like this: import win32com.client import time connect = win32com.client.Dispatch("ADODB.Connection") recordset = win32com.client.Dispatch("ADODB.Recordset") connect.Open("Driver={SQLServer};Server=devserver;Database=VidVisitation;UID=sa;PWD=;") datestring = time.strftime("%m/%d/%Y") sql = "Select * from VisSchedule where SDATE='" + datestring +"'" recordset.Open(sql,connect) Now I want to receive events for the recordset when the recordset changes. Here is the IDL for the event: [id(0x0000000e)] HRESULT RecordsetChangeComplete( [in] EventReasonEnum adReason, [in] Error* pError, [in, out] EventStatusEnum* adStatus, [in] _Recordset* pRecordset); How do I wire up the recordset I have created to receive this event? From bobrien18 at yahoo.com Wed Mar 8 14:05:20 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 8 Mar 2006 11:05:20 -0800 Subject: reshape an array? Message-ID: <1141844720.242225.322220@p10g2000cwp.googlegroups.com> I have a 2D array. Say it is 10x10 and I want a 1D Array of 100 elements... What is the syntax? oneD = reshape(twoD, (100,1)) or oneD = reshape(twoD, (1,100)) One I guess is the transpose of the other but both seem to be arrays of arrays... help?! From tim.leeuwvander at nl.unisys.com Fri Mar 24 08:11:53 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 24 Mar 2006 05:11:53 -0800 Subject: Bitwise OR? In-Reply-To: References: <1143187977.384459.225840@i40g2000cwc.googlegroups.com> <1143190128.783253.62430@i40g2000cwc.googlegroups.com> Message-ID: <1143205913.672328.225990@t31g2000cwb.googlegroups.com> I wonder what causes one version to be faster for positive, and the other faster for negative numbers? I can see that the pos-version doesn't make as many iterations as the neg version, but it doesn't pad the length of the result to the requested number of digits and potentially produces more digits. I also wonder if it wouldn't be faster to put the numbers into a list and join the list into a string -- did you test with that? Cheers, --Tim From brian at rkspeed-rugby.dk Wed Mar 8 07:19:20 2006 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: Wed, 08 Mar 2006 13:19:20 +0100 Subject: Simple questions on use of objects (probably faq) References: Message-ID: Steven D'Aprano writes: Thanks for the answers. They are very useful. > self.args = (x, y, z) # save a copy of the arguments As always python makes it easy. >>>> max(obj.lister()) > 4 Actually I wanted to get the maximum of attributes of several instances. List comprehension is the answer. > method. Do this instead: > > ys.append(s.x) I always get confused by extend and append. > this is wasteful. Just call the function at the end, after collecting all > the values: Easier indeed. > for index, value in enumerate(ys[:-1]): > yz.append(ys[index+1] - value) > I will need to study enumerate a bit. > By the way, don't be shy about using more meaningful names for variables. > ys and yz are terribly similar, and is a bug waiting to happen. I know, and in the real code I use better names. > You can't use continue in there, it isn't a null-op. Perhaps you wanted > "pass"? Yes. >> yz=[y[:-1].x-y[1:].x] > > How about, before trying to invent short cuts, you actually learn some of > the Python syntax? The [x:y] syntax already has a meaning to Python, > just not what you want. Perhaps it is not the same, but quite close. In matlab .* is element-by-element multiplication. I was thinking about a .- operator. wouldn't that make sense here? > Also, while everything in Python is an object, you don't *have* to use > object oriented techniques. In the real problem the class is: class Stream: def __init__(self,T_start,T_end,Q_dot): self.T_start=T_start self.T_end=T_end self.Q_dot=Q_dot self.mcp=abs(Q_dot/(T_start-T_end)) if T_start>T_end: self.type='hot' else: self.type='cold' and I thought it would make sense to store this a objects. Otherwise I would need to store each stream as a list is refer their indexes. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk From aleaxit at yahoo.com Thu Mar 30 11:48:02 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 30 Mar 2006 08:48:02 -0800 Subject: a hobbyist's dilemma References: <1hd06ks.9fwqmuzmmesvN%aleaxit@yahoo.com> Message-ID: <1hd08f2.4an4v51wwn6rdN%aleaxit@yahoo.com> John Salerno wrote: ... > > Instead of hacking away on your own, I suggest you look around > > sourceforge and other such repositories of open-source programs: find ... > Great idea. It would be fun to actually contribute something to the > community, but I don't think I'm quite at that level yet, unless it's > more of an 'assistant programmer' role, i.e. get the programmer's > coffee. :) Give it a try! Community is your greatest resource, after all. Alex From mateom at gmail.com Wed Mar 15 16:11:58 2006 From: mateom at gmail.com (mateom at gmail.com) Date: 15 Mar 2006 13:11:58 -0800 Subject: Queue limitations? References: <1142440071.355627.120450@z34g2000cwc.googlegroups.com> Message-ID: <1142457118.838881.313860@v46g2000cwv.googlegroups.com> > the queue holds references to the images, not the images themselves, > so the size should be completely irrelevant.I use one instance of imageQueue. hmmm.. true. And it also fails when I use PIL Image objects instead of arrays. Any idea why compressing the string helps? I'm using one instance of imageQueue. -Thanks From jdhunter at ace.bsd.uchicago.edu Thu Mar 30 00:08:08 2006 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 29 Mar 2006 23:08:08 -0600 Subject: Matplotlib: Histogram with bars inside grid lines...how?? References: <1143678532.482987.249610@i39g2000cwa.googlegroups.com> <87y7yshcz4.fsf@peds-pc311.bsd.uchicago.edu> <1143690538.239449.93270@i40g2000cwc.googlegroups.com> <1143691909.004162.295350@g10g2000cwb.googlegroups.com> Message-ID: <87lkusjz9j.fsf@peds-pc311.bsd.uchicago.edu> >>>>> "Enigma" == Enigma Curry writes: Enigma> pylab.xlim(0.5,6.5) should be: Enigma> pylab.xlim(min_x-(bar_width/2),max_x+(bar_width/2)) Glad it's working better for you -- just a couple more smallish hints. You might prefer to have your grid lines behind, rather than above the bars. In that case create the subplot or axes with the axisbelow=True kwarg. Despite the fact that you found the kwargs a little annoying at first, you will probably come to love them. matplotlib makes very heavy use of them and they are very useful since they allow matplotlib to usually do the right things while exposing most of the settings to you. Eg plot(x, y, linewidth=2, linestyle='--', marker='o', markerfacecolor='r', markeredgecolor='g' markeredgewith=2, markersize=10) and so on. There are lots of properties you can set on almost every command. Because noone wants to type all that, you can use aliases plot(x, y, lw=2, ls='--', marker='o', mfc='r', mec='g', mew=2, ms=10) Secondly, in your example, you are relying implicitly on matplotlib to pick integer ticks for the xaxis. It's doing it right in this example, but might prefer other tick locations for other examples depending on your x_values. So set xticks explicitly. Below is a slightly modified example showing these two ideas. You also might want to consider joining the mailing list at http://lists.sourceforge.net/mailman/listinfo/matplotlib-users since you appear to be a little finicky about your figures :-) def ryan_hist(data, bar_width, min_x, max_x): """ Create a frequency histogram over a continuous interval min_x = the low end of the interval max_x = the high end of the interval bar_width = the width of the bars This will correctly align the bars of the histogram to the grid lines of the plot """ #Make histogram with bars of width .9 and center #them on the integer values of the x-axis bins = pylab.nx.arange(1-(bar_width/2),max(data)) pylab.subplot(111, axisbelow=True) n,bins,patches = pylab.hist(data, bins, width=bar_width) #Make Y axis integers up to highest n pylab.yticks(pylab.arange(max(n))) pylab.xticks(pylab.arange(max(n)+1)) pylab.axis('scaled') pylab.xlim(min_x-(bar_width/2),max_x+(bar_width/2)) pylab.grid() pylab.show() From sathyaish at gmail.com Mon Mar 20 01:30:03 2006 From: sathyaish at gmail.com (Sathyaish) Date: 19 Mar 2006 22:30:03 -0800 Subject: ** Operator In-Reply-To: <1hcgw5p.1ufznwe1lxeagfN%aleaxit@yahoo.com> References: <1142833145.976550.104830@v46g2000cwv.googlegroups.com> <1142833540.860154.137040@u72g2000cwu.googlegroups.com> <1hcgw5p.1ufznwe1lxeagfN%aleaxit@yahoo.com> Message-ID: <1142836203.598470.310950@u72g2000cwu.googlegroups.com> Thanks, Alex. From anand.chittu at gmail.com Wed Mar 22 10:00:28 2006 From: anand.chittu at gmail.com (Anand) Date: 22 Mar 2006 07:00:28 -0800 Subject: multiple assignment In-Reply-To: References: <1143018514.721434.246450@i39g2000cwa.googlegroups.com> Message-ID: <1143039628.881127.25010@u72g2000cwu.googlegroups.com> > You're right, that would not be so far off. > But then, the following should be also supported: > > *x, y = a # x, y = a[:-1], y = a[-1] > x, *y, z = a # x, y, z = a[0], a[1:-1], a[-1] > > Of course, there can be only one variable with an asterisk. > (But note that in the situation of a function taking parameters, that > variable must always be the last.) Same argument can be applied for functions also. whats wrong in having some thing like this? def f(x, *y, z): pass I think there is a problem in both these cases. > But I don't know if this is really useful enough... I think it is really useful. One which i encountered was there is a file where each line has tokens separated by commas. First token is the id and i want to use it in a special way. Wouldn't it be nice to say id, *tokens = line.split(',') than tokens = line.split(',') id = tokens.pop(0) - anand From steven.bethard at gmail.com Thu Mar 16 10:08:32 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 16 Mar 2006 08:08:32 -0700 Subject: Python Documentation Standards In-Reply-To: References: Message-ID: Colin J. Williams wrote: > Doc strings provide us with a great opportunity to illuminate our code. > > In the example below, __init__ refers us to the class's documentation, > but the class doc doesn't help much. It doesn't? >>> print list.__doc__ list() -> new list list(sequence) -> new list initialized from sequence's items What is it you were hoping to see in constructor documentation? STeVe From eugene at boardkulture.com Tue Mar 21 11:15:06 2006 From: eugene at boardkulture.com (3KWA) Date: 21 Mar 2006 08:15:06 -0800 Subject: New-style Python icons In-Reply-To: <1142957161.302935.27210@i39g2000cwa.googlegroups.com> References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> <1142938350.321554.69260@t31g2000cwb.googlegroups.com> <1142942389.170814.196640@z34g2000cwc.googlegroups.com> <1142957161.302935.27210@i39g2000cwa.googlegroups.com> Message-ID: <1142957706.611911.266220@j33g2000cwa.googlegroups.com> Thanks a lot! (Still think 2.5 could have spunky new icons:) EuGeNe From duncanm255 at hotmail.com Wed Mar 1 15:47:26 2006 From: duncanm255 at hotmail.com (D) Date: 1 Mar 2006 12:47:26 -0800 Subject: newbie question In-Reply-To: References: <1141242700.105093.317210@t39g2000cwt.googlegroups.com> Message-ID: <1141246046.591750.315550@i39g2000cwa.googlegroups.com> Yep, that should work. Just keep in mind that if python.exe is not in your path, you will need to either specify the entire path to it (i.e. 'C:\python24\python C:\path\to\script\myscript.py'), or cd into its directory first (i.e. if you want to just run 'python C:\path\to\script\myscript.py'). Doug From peter at engcorp.com Sat Mar 18 08:26:35 2006 From: peter at engcorp.com (Peter Hansen) Date: Sat, 18 Mar 2006 08:26:35 -0500 Subject: filter list fast In-Reply-To: <4827udFi2qosU1@uni-berlin.de> References: <1142675680.468064.167930@v46g2000cwv.googlegroups.com> <1142678088.792548.96610@z34g2000cwc.googlegroups.com> <4827udFi2qosU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >>Both of these techniques are O(n^2). You can reduce it to O(n log n) >>by using sets: >> >>>>>set2 = set(list2) >>>>>[x for x in list1 if x not in set2] >> >>Checking to see if an item is in a set is much more efficient than a >>list. > > Is the set-lookup reliably O(log n)? I was under the impression that it is > hash-based, and this should be O(1) usually, but couldbve O(n) worst-case > (hash the same for _all_ entries). That's largely a theoretical concern. Google for something like '''dict worst-case performance "tim peters"''' to learn more. (The third article there (no doubt obsolete in some ways, given that it was in 2000) says that Python "keeps at least 1/3 of the internal hash table entries unused, making collisions very rarely a problem... It's possible to contrive keys that will cause collisions systematically ... but unlikely to happen by accident in 2.0") -Peter From python-url at phaseit.net Fri Mar 17 17:51:24 2006 From: python-url at phaseit.net (Cameron Laird) Date: Fri, 17 Mar 2006 22:51:24 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 17) Message-ID: QOTW: "Generally, you should always go for whatever is clearest/most easily read (not just in Python, but in all languages)." - Timothy Delaney "You will find as your programming experience increases that the different languages you learn are appropriate for different purposes, and have different advantages and disadvantages. Python excels at expressing algorithms in an unambiguous and easily-readable way." - Steve Holden Is Python a viable extension language for Java? Ravi Teja expertly outlines the possibilities: http://groups.google.com/group/comp.lang.python/msg/54ad155bc138c8d2 "In order to facilitate small groups working on specific Python-in-Education projects, we have launched an edupython list on google groups." This is a hands-on complement to the more "philosophical" edu-sig. http://groups.google.com/group/edupython mailto:edupython at googlegroups.com One interesting use of Python--at least to software workers--is to manage texts written in *other* languages. Fredrik Lundh and Roman Yakovenko present good approaches for the C++ case: http://groups.google.com/group/comp.lang.python/msg/913eb2563b815745 http://groups.google.com/group/comp.lang.python/msg/2b74c8355fc5c25a Pascal and Python? Sure: http://groups.google.com/group/comp.lang.python/browse_thread/thread/9806ed054493d6a6/ Uche Ogbuji details XPath, *XSLT, XQuery, ... capabilities: http://groups.google.com/group/comp.lang.python/browse_thread/thread/51b0fcdc7df8a34e/ ======================================================================== 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 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://python.sourceforge.net/peps/pep-0042.html 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 venkatbo at yahoo.com Wed Mar 1 12:28:01 2006 From: venkatbo at yahoo.com (venkatbo at yahoo.com) Date: 1 Mar 2006 09:28:01 -0800 Subject: Cross compile generation of .pyc from .py files... In-Reply-To: References: <1141176107.234667.93210@e56g2000cwe.googlegroups.com> Message-ID: <1141234081.046271.326160@i39g2000cwa.googlegroups.com> Terry Reedy wrote: > ... > I am under the impression that .pyc files are system independent. > Have you tried simply copying them over? > > tjr Hi Terry, It appears that python on the target ppc system is expecting to see ppc-related info in the .pyc files. These .pyc were generated at cross compile time (on i686 system) and packaged, deployed, installed on the ppc system. The "...has bad magic..." appears to indicate that ppc-version of python is expecting to see ppc-specific .pyc files, but is encountering i686-specific .pyc files... For some reason, the cross-compile step that results in the .pyc files is not generating them for the proper ppc-target, but is building them for the i686 system where they were being cross-compiled... Thanks, /venkat From vinjvinj at gmail.com Fri Mar 10 13:58:02 2006 From: vinjvinj at gmail.com (vinjvinj) Date: 10 Mar 2006 10:58:02 -0800 Subject: Performance impact of using decorators In-Reply-To: References: <1142003515.886709.290360@j33g2000cwa.googlegroups.com> <1142008926.296541.111550@j52g2000cwj.googlegroups.com> Message-ID: <1142017082.086440.78270@z34g2000cwc.googlegroups.com> >>what exactly made you think that Python would be able to run your >>code *without* calling your function ? I was hoping that when the compiler finds decorators with wrapers that have the same signature it can some how "magically" combine them into one function (which gets called at run time) and not have 5 nested function calls. That is similar to what I will have to do eventually. Given python's dynamic nature, I'm sure there are reasons why this is not done. From fabiofz at gmail.com Sat Mar 18 18:27:05 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Sat, 18 Mar 2006 20:27:05 -0300 Subject: How to change echo in python prompt In-Reply-To: References: Message-ID: Hi... Found out (sys.ps1 and sys.ps2 control that). Cheers, Fabio On 3/18/06, Fabio Zadrozny wrote: > > Hi All, > > Does someone know if there is some way to supress the '>>>' and '...' in > the python prompt (while actually forcing prompts with -i)? > > -- and all that in a non-platform dependent way ;-) > > Thanks, > > Fabio > -------------- next part -------------- An HTML attachment was scrubbed... URL: From felipe.lessa at gmail.com Mon Mar 20 09:14:35 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Mon, 20 Mar 2006 11:14:35 -0300 Subject: ANNOUNCE: xlrd 0.5.2 -- extract data from Excel spreadsheets In-Reply-To: <441E99B7.1050506@lexicon.net> References: <441c7714$1_2@newspeer2.tds.net> <441C9F4D.1030203@lexicon.net> <441ccb61$1_3@newspeer2.tds.net> <441D23F2.7090808@lexicon.net> <1142850490.058912.138560@e56g2000cwe.googlegroups.com> <441E865D.20508@lexicon.net> <1142852445.087922.250140@g10g2000cwb.googlegroups.com> <441E8F48.6070404@lexicon.net> <1142854637.666293.205330@u72g2000cwu.googlegroups.com> <441E99B7.1050506@lexicon.net> Message-ID: <1142864075.3929.0.camel@kenshin> Em Seg, 2006-03-20 ?s 23:01 +1100, John Machin escreveu: > *ALL* [ho ho chuckle chuckle] > you need to do is step through the tokens and do something with the ones > that contain references. And contribute back the code? =) -- Felipe. From python.list at tim.thechases.com Thu Mar 2 16:45:45 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 02 Mar 2006 15:45:45 -0600 Subject: how do you move to a new line in your text editor? In-Reply-To: <20060302151811.0b1ce977.lists@elehack.net> References: <%ZGNf.1711$No6.40016@news.tufts.edu> <20060302151811.0b1ce977.lists@elehack.net> Message-ID: <44076789.4000700@tim.thechases.com> > I use Vim, use spaces, and have no problems. It has a > shorttabstop option, which causes backspace to backspace > to the preceding multiple of spaces when the > curser is after a set of spaces at the beginning of the > line. It feels like I'm using tabs, but I'm not. In addition, within insert-mode in vim, you can use control+D and control+T to exdent/indent the current one 'shiftwidth' worth. If your 'shiftwidth' setting is the same as your 'tabstop' setting, you'll get the expected behavior. There are also settings to control whether tabs get interpreted as spaces or vice-versa (see ":help expandtab"). I presume Emacs has similar settings. However, Vim can be tweaked to handle whatever style you're comfortable with (or whatever style management shoves down on you). The "shiftwidth = tabstop" also holds for the ">" and "<" operators, so in Normal mode, you can use ">>" to indent the current line, or "<3j" to exdent the current line and the three below it. All sorts of magic can be worked with this :) > Also, there's some Python indenting/folding macros I > picked up from Vim Online (don't remember where exactly), > that provide an indent/outdent pair of key mappings, > which also work perfectly with my usage of 4 spaces. If you pop over to www.vim.org you'll find a search functionality to search both the "tips" and "scripts" section. Just searching for "python" yields a bounty of fun. For folding, because python uses indenting, you can just set your 'foldmethod' setting to "manual". Okay...this has drifted just a wee spot off-topic. However, the vim mailing list is a friendly place--so if you have any questions, feel free to drop in. -tkc From cito at online.de Wed Mar 22 04:45:45 2006 From: cito at online.de (Christoph Zwerschke) Date: Wed, 22 Mar 2006 10:45:45 +0100 Subject: multiple assignment In-Reply-To: <1143018514.721434.246450@i39g2000cwa.googlegroups.com> References: <1143018514.721434.246450@i39g2000cwa.googlegroups.com> Message-ID: Anand schrieb: > Suppose i have a big list and i want to take tke the first one and rest > of the list like car/cdr in lisp. > is there any easy way to do this in python? > > Only way i know is > > a = range(10) > x, y = a[0], a[1:] You have so many higher-level ways to access and iterate through lists in Python, that you normally just don't need to do things like that. Also, in the frequent case where y=a, you can just write x = a.pop(0). > Why can't python support something like this: > > x, *y = a > > This is not really a new concept to python, infact when calling a > function which takes variable arguments, it is used in a similar way. You're right, that would not be so far off. But then, the following should be also supported: *x, y = a # x, y = a[:-1], y = a[-1] x, *y, z = a # x, y, z = a[0], a[1:-1], a[-1] Of course, there can be only one variable with an asterisk. (But note that in the situation of a function taking parameters, that variable must always be the last.) But I don't know if this is really useful enough... -- Christoph From webraviteja at gmail.com Wed Mar 22 23:34:22 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 22 Mar 2006 20:34:22 -0800 Subject: UML from py sources In-Reply-To: References: Message-ID: <1143088462.689660.177790@i40g2000cwc.googlegroups.com> Not to interrupt the valuable lesson with Google :-) Boa Constructor. From aleaxit at yahoo.com Sun Mar 5 14:12:56 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Mar 2006 11:12:56 -0800 Subject: Python advocacy in scientific computation References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> <1141583453.403143.189400@i40g2000cwc.googlegroups.com> Message-ID: <1hbq48q.pq04qg1qldmc7N%aleaxit@yahoo.com> sturlamolden wrote: > just a toy. And as Matlab's run-time does reference counting insted of > proper garbage collection, any datastructure more complex than arrays > are sure to leak memory (I believe Python also suffered from this as > some point). Yes, that was fixed in the move from 1.5.2 to 2.0 (I don't recall if the intermediate short-lived 1.6 also fixed it, but nobody used that anyway;-). > Matlab is not useful for anything except plotting data > quickly. And as for the expensive license, I am not sure its worth it. > I have been considering a move to Scilab for some time, but it too > carries the burden of working with a flawed language. There was a pyscilab once, still around at , but I don't think it ever matured beyond a "proof of concept" release 0.1 or something. Alex From fake at nospam.no Mon Mar 6 11:33:20 2006 From: fake at nospam.no (Blackbird) Date: Mon, 6 Mar 2006 17:33:20 +0100 Subject: %r Message-ID: <75-dnc5y7fLN-ZHZRVnzvA@telenor.com> I'm trying to get a complete grip on %r. Is it true that the two programs a = '*anything the parser accepts*' print '%r' % a vs. a = r'*anything the parser accepts*' print "'%s'" % a always produce the same output, where *anything the parser accepts* can be replaced with, well, anything the parser accepts? From sybrenUSE at YOURthirdtower.com.imagination Mon Mar 13 07:37:36 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 13 Mar 2006 13:37:36 +0100 Subject: Please, I Have A Question before I get started References: <40l912h0aubfgai2en7n465ml9olg746h9@4ax.com> Message-ID: Skipper enlightened us with: > I can not believe that there isn't a GUI programing tool that will > allow me to build GUI apps There are plenty of them. > just like I use Dreamweaver to build a web page Which produces horrible HTML. 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 benji at benjiyork.com Sun Mar 19 17:17:32 2006 From: benji at benjiyork.com (Benji York) Date: Sun, 19 Mar 2006 17:17:32 -0500 Subject: Have you ever considered of mousing ambidextrously? In-Reply-To: References: <1142660417.662387.73350@j33g2000cwa.googlegroups.com> Message-ID: <441DD87C.3090701@benjiyork.com> Aahz wrote: > Heh. When possible, my work situation includes two computers, each with > their own keyboard and mouse. To put the keyboards as close together as > possible, the mice go on the outside. I prefer a similar setup with 2 duel monitor PCs (one Linux, one Windows), but use x2vnc to control both with one keyboard and mouse. Unfortunately neither x2vnc or Synergy really fulfill my needs though, so I'm working on a replacement. Actually I'm writing this email instead of working on it, back to the (Vim) mines. -- Benji York From quale1 at charter.net Sat Mar 18 02:05:00 2006 From: quale1 at charter.net (Doug Quale) Date: 18 Mar 2006 01:05:00 -0600 Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1142589945.078364.32870@i39g2000cwa.googlegroups.com> <1142599685.186209.177630@j33g2000cwa.googlegroups.com> <1142647977.696295.124650@i40g2000cwc.googlegroups.com> Message-ID: <87u09w9qsj.fsf@shiva.mad.wi.charter.com> "funkyj" writes: > One advantage of a generator over filtering the full product is that I, > as the user of the generator, am not obligated to iterate over the > entire solution space. > > Are there other _practical_ advantages of generators over mapping & > filtering complete sets? Storage. You can iterate over problem spaces much too large to fit in memory. Also generate + iterate can be faster because of reduced memory pressure. From grflanagan at yahoo.co.uk Wed Mar 1 13:00:27 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 1 Mar 2006 10:00:27 -0800 Subject: Accessing 'mangled' class attrbutes References: <1141226955.820389.87860@z34g2000cwc.googlegroups.com> <1141231824.077785.97490@e56g2000cwe.googlegroups.com> Message-ID: <1141236027.879054.139460@t39g2000cwt.googlegroups.com> danmcleran at yahoo.com wrote: > >>Is there any simple way round this situation in general? > > It might be safer to use composition instead of inheritance in this > case. Assuming that XMLWriter has a write method to write what you > want, you could hold a reference to an XMLWriter within your class and > pass along write command like: > > writer = XMLWriter() > writer.write(stuff) No, XMLWriter doesn't have a 'write' method, if it did I could have done: super(HtmlWriter, self).write(stuff) I think the XMLWriter class has been designed so you can't just write any old text because this better ensures that tags are properly closed and so on. There is a public 'data' method: writer.data( text ) but it escapes angle brackets, and what i wanted was to write ' Hello all, I would like to set a Windows Environment variable for another (non-child) process. This means that the following *doesn't* work : :: os.environ['NAME'] = value In the ``win32api`` package there is a ``GetEnvironmentVariable`` function, but no ``SetEnvironmentVariable``. Any options ? Fuzzyman http://www.voidspace.org.uk/python/index.shtml From tom.willis at gmail.com Thu Mar 9 10:33:12 2006 From: tom.willis at gmail.com (Thomas G. Willis) Date: Thu, 9 Mar 2006 10:33:12 -0500 Subject: Python Evangelism In-Reply-To: <288425520603090642y7db7824cy4de5365f36eb1605@mail.gmail.com> References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> <288425520603090642y7db7824cy4de5365f36eb1605@mail.gmail.com> Message-ID: I used to get all fired up about the language I love. And I'd evangelize a bit. But I'm getting too old for that. Energy could be better spent utilizing the tools you like. Sort of a "If you build it, they will come..." kind of thing. I get particulalry annoyed now with linux when I start up synaptic and my choices are cluttered with several programs who might help me in some way, but the only difference described in the description is that they were implemented in language XXX. I don't really consider that a choice, it's more noise than anything. On the other hand, programs that really do seem to be valuable don't seem to be screaming about what language they are written in. I had no idea the original BitTorrent was written in python, or scons when I installed it. Bittorrent helps me get files faster, scons helps me build ardour. They could be written in lisp for all I care, it benefits me nonetheless. My opinion is that providing programs that benefit people in some way could go a lot farther in promoting the language than propoganda about what you can do with the language. Shouting about the potential of the tools will only get you so far. Rails is the killer framework of the moment. So what? Where's the killer app that helps me do something new? All i hear about is people writing frameworks on top of rails to do things that can already be done. CMS's for example, there are some written in rails. To my knowledge none of them are mature yet, and thus the only "selling" point I hear about "written in rails". Benefit to me as a user still = 0%. How about this? someone write an interface to the quake3 engine, and make it damn easy for kids to write games and game mods. or... Make it possible to write ladspa plugins so that I can write crazy effects for ardour. or... an itunes like music manager that doesn't lock all my music away and handles m3u files properly out of the box. With a plug in system so people can extend it. don't even mention it was done in python, if it's done right, the true value will be apparent and your users will do the evangelizing for you. OK, I will now return to my happy place. :) -- Thomas G. Willis ----------------------------------------------- http://i-see-sound.com http://tomwillis.sonicdiscord.com America, still more rights than North Korea -------------- next part -------------- An HTML attachment was scrubbed... URL: From john_sips_tea at yahoo.com Tue Mar 21 16:42:01 2006 From: john_sips_tea at yahoo.com (john_sips_tea at yahoo.com) Date: 21 Mar 2006 13:42:01 -0800 Subject: doctest, unittest, or if __name__='__main__' In-Reply-To: References: <1142974528.143287.326360@e56g2000cwe.googlegroups.com> Message-ID: <1142977320.983856.179630@g10g2000cwb.googlegroups.com> > and you can kill two birds with one stone. By that, do you mean you can write your tests and your docstrings in one shot with doctest? > I would like to see yet another alternatise such as py.test > in the standard lib, Ah: http://codespeak.net/py/current/doc/home.html From bdesth.quelquechose at free.quelquepart.fr Sun Mar 19 18:28:09 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 20 Mar 2006 00:28:09 +0100 Subject: Counting number of each item in a list. In-Reply-To: <1142796177.711806.41150@g10g2000cwb.googlegroups.com> References: <1142772092.958602.272260@e56g2000cwe.googlegroups.com> <441d58f7$0$13046$626a54ce@news.free.fr> <1142774630.426660.19970@t31g2000cwb.googlegroups.com> <441d6342$1_3@newspeer2.tds.net> <441d9408$0$20430$636a55ce@news.free.fr> <441dab21$0$27059$626a54ce@news.free.fr> <1142796177.711806.41150@g10g2000cwb.googlegroups.com> Message-ID: <441dbc27$0$7108$626a54ce@news.free.fr> Justin Azoff a ?crit : > Bruno Desthuilliers wrote: > >> My solution seems to be faster than Paul's >>one (but slower than bearophile's), be it on small, medium or large lists. > > > Your version is only fast on lists with a very small number of unique > elements. > > changing mklist to have > items = range(64) instead of the 9 item list and re-timing you will get > "better" results: > > A100 (10000 times): 7.63829684258 > B100 (10000 times): 1.34028482437 > C100 (10000 times): 0.812223911285 > > A10000 (100 times): 9.78499102592 > B10000 (100 times): 1.26520299911 > C10000 (100 times): 0.857560873032 > > A1000000 (10 times): 87.6713900566 > B1000000 (10 times): 12.7302949429 > C1000000 (10 times): 8.35931396484 > > Lol ! So much for my benchmarking skills :-/ From nvasiliev at whiteriversoft.com Thu Mar 30 02:32:12 2006 From: nvasiliev at whiteriversoft.com (Nicolay A. Vasiliev) Date: Thu, 30 Mar 2006 11:32:12 +0400 Subject: GUI in python In-Reply-To: <1143692752.137979.30090@g10g2000cwb.googlegroups.com> References: <1143670803.148098.21940@z34g2000cwc.googlegroups.com> <1143692752.137979.30090@g10g2000cwb.googlegroups.com> Message-ID: <442B897C.8030604@whiteriversoft.com> Hello! I think this library is enough old, isn't it? Version 0.72 was released on 2004-06-20. Nicolay riplin at Azonic.co.nz wrote: > For quick, no learning curve, simple: > > http://www.ferg.org/easygui/ > > From msoulier at gmail.com Thu Mar 9 10:21:00 2006 From: msoulier at gmail.com (msoulier) Date: 9 Mar 2006 07:21:00 -0800 Subject: why no block comments in Python? In-Reply-To: References: <_MCPf.1749$No6.40293@news.tufts.edu> Message-ID: <1141917660.221099.110660@z34g2000cwc.googlegroups.com> > (and if you don't, you can quickly comment out regions by putting them > inside a triple-quoted string.) Although that will use up memory, as opposed to a comment. Still, it's simple enough in an editor like Vim or Emacs to highlight a region, and define a macro to add/remove #s. Any Python IDE should certainly have this capability. Mike From codecraig at gmail.com Wed Mar 8 12:34:14 2006 From: codecraig at gmail.com (abcd) Date: 8 Mar 2006 09:34:14 -0800 Subject: PyCon2006 - will the content be available for download? In-Reply-To: <1141832817.145771.153870@u72g2000cwu.googlegroups.com> References: <1141824493.358952.106780@i40g2000cwc.googlegroups.com> <440EDD81.9040708@mxm.dk> <1141832817.145771.153870@u72g2000cwu.googlegroups.com> Message-ID: <1141839254.779163.27290@i39g2000cwa.googlegroups.com> well actually, the site looked promising...only problem is no talks have audio, video or handouts available (at least right now). oh well. From fredrik at pythonware.com Wed Mar 15 00:45:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Mar 2006 06:45:02 +0100 Subject: elementtree and gbk encoding References: Message-ID: Steven Bethard wrote: > I'm having trouble using elementtree with an XML file that has some > gbk-encoded text. (I can't read Chinese, so I'm taking their word for > it that it's gbk-encoded.) I always have trouble with encodings, so I'm > sure I'm just screwing something simple up. Can anyone help me? absolutely! pyexpat has only limited support for non-standard encodings; the core expat library only supports UTF-8, UTF-16, US-ASCII, and ISO-8859-1, and the Python glue layer then adds support for all byte-to-byte en- codings support by Python on top of that. if you're using any other encoding, you need to recode the file on the way in (just decoding to Unicode doesn't work, since the parser expects an encoded byte stream). the approach shown on this page should work http://effbot.org/zone/celementtree-encoding.htm except that it uses the new XMLParser interface which isn't available in ET 1.2.6, and the corresponding XMLTreeBuilder interface in ET doesn't support the encoding override argument... the easiest way to fix this is to modify the file header on the way in; if the file has an header, rip out the header and recode from that encoding to utf-8 while parsing. From lycka at carmen.se Thu Mar 2 04:45:58 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 02 Mar 2006 10:45:58 +0100 Subject: Best python module for Oracle, but portable to other RDBMSes In-Reply-To: <1141242710.730153.279490@z34g2000cwc.googlegroups.com> References: <1140818561.458171.237850@p10g2000cwp.googlegroups.com> <1140826717.186051.261430@i39g2000cwa.googlegroups.com> <1141242710.730153.279490@z34g2000cwc.googlegroups.com> Message-ID: dananrg at yahoo.com wrote: > This is from a database I didn't design and can't change. The problem > is that the ODBC module suffixes an "L" to any integer returned that > was defined as data type number(p). For example, an integer stored as: > 56 will be returned as 56L. Numbers that were specified as > number(p,s), the module has no problem with. > > Anyone know why this would happen? I'm sure the Python tutorial explains the difference between integer and long types. Fields of type NUMBER or DECIMAL might well be larger than sys.maxint, so you always get longs back when you fetch data from such a column. This is as it should be. What seems to be the problem? If you actually get a suffixed L in the resulting text file, you are using a strange way to convert your data to text. You aren't simply printing lists or tuples are you? Then other types, such as datetime objects will also look bizarre. (Not that the ancient odbc would support that...) You might want to look at the csv module for text export. From no-spam at no-spam-no-spam.com Thu Mar 2 13:52:34 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 02 Mar 2006 19:52:34 +0100 Subject: wxPython memory footprint? - Re: Write a GUI for a python script? In-Reply-To: <1141315236.636933.149430@i39g2000cwa.googlegroups.com> References: <1141315236.636933.149430@i39g2000cwa.googlegroups.com> Message-ID: ianar? wrote: > wxPython is another good option, especially since there is > boa-constructor, which is a great GUI builder, almost makes it too easy > to make a nice looking app in no time at all. > > http://www.wxpython.org/download.php > > http://boa-constructor.sourceforge.net/ > > if you decide to give wxPython a go, make sure to download the demo, it > has tons of usefull code samples. What is the minimal memory footprint of a Hello World wxPython app meanwhile (when you cx_freeze/py2exe it) ? Can you debug & call functions interactively from e.g. Pythonwin while a wxPython app is running. ( When I made a test with wxPython some years ago, it had no option to step/share its Messageloop. Interaction was "crust"y and I didn't manage to get smooth debugging (on Windows). ) Robert From steve at hastings.org Thu Mar 23 20:36:23 2006 From: steve at hastings.org (Steve R. Hastings) Date: Thu, 23 Mar 2006 17:36:23 -0800 Subject: Announcing xe and PyFeed, for XML and syndication feeds Message-ID: xe.py is a Python module to make it very easy to work with XML. I have attempted to make xe classes very Pythonic and intuitive. xe is intended for working with structured XML, such as syndication feed files, but I have added some support for unstructured XML as well. Example: >>> import xe >>> bird = xe.TextElement("bird") >>> bird.attrs["type"] = "Norwegian Blue" >>> bird.text = "just resting" >>> print bird just resting >>> cheese = xe.TextElement("cheese") >>> cheese.text = "a bit runny" >>> examples = xe.NestElement("examples") >>> examples.bird = bird >>> examples.cheese = cheese >>> print examples just resting a bit runny PyFeed is a Python module package set with modules for working with syndication feeds. These modules use the xe classes. PyFeed currently includes modules for working with Atom feeds, RSS 2.0 feeds, OPML 1.0 files, and OPML files. Example: >>> import feed.rss >>> channel = feed.rss.Channel() >>> lst_errors = [] >>> channel.import_xml("http://www.planetpython.org/rss20.xml", lst_errors) >>> print len(lst_errors) or "No errors!" No errors! >>> print channel.title Unofficial Planet Python >>> print len(channel.items) 45 >>> print channel.items[0].title.text Mike Fletcher: Minor TwistedSNMP release is up >>> item = channel.items[0] >>> print item.pub_date.text Thu, 23 Mar 2006 15:45:31 -0800 >>> # note that the date printed with "-0800", my time zone ... >>> item.pub_date.update() >>> print item.pub_date Thu, 23 Mar 2006 17:15:55 -0800 >>> item.pub_date = "not a valid timestamp" Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python/xe.py", line 1327, in __setattr__ o.direct(value) File "/usr/local/lib/python/xe.py", line 1148, in direct raise ValueError, "value must be a valid timestamp string" ValueError: value must be a valid timestamp string >>> item.pub_date = "01 Jan 2006 08:01:23 GMT" >>> print item.pub_date.text Sun, 01 Jan 2006 00:01:23 -0800 >>> print item.pub_date.tf 1136102483.0 If there is any interest in these modules, I'll probably put them on Sourceforge.net and on the Cheese Shop someday. For now, they live on my personal web space: http://www.blarg.net/~steveha/xe.html http://www.blarg.net/~steveha/pyfeed.html I look forward to any feedback. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From gherzig at fmed.uba.ar Fri Mar 10 09:51:52 2006 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Fri, 10 Mar 2006 11:51:52 -0300 Subject: operator creation? Message-ID: <1142002312.16170.12.camel@linux.site> Hi all. Ill try to explain mi situation: Lets say i have an DB object, who implements the querys to the database trough a method called DBObject.doQuery. On the other hand, i have 50 sql functions stored in the database. So i can call DBObject.doQuery('select * from my_sql_function()')...Ok, what do i want to achieve, is some mecanism to be able to call DBObject.my_sql_function(), but without actually having to declare the method called "my_sql_function". May be with creating a `->' operator... maybe overrwriting the '.' operator... Im not shure. If someone understand my problem (and my poor english), please help :) Gerardo From sullivanz.pku at gmail.com Sat Mar 11 15:23:28 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 11 Mar 2006 12:23:28 -0800 Subject: How to refer to the function object itself in the function per se? Message-ID: <1142108608.559879.45560@i39g2000cwa.googlegroups.com> When debugging using 'print' statement, I usually want to print some important values together with the function name as the context of the values printed out. So my hope is that I could get the name of the function. Since every function object actually has a private __name__ attribute that gives its name, but when I print __name__ in a function, it usually print the public module-level __name__ attribute, ie, 'main', rather than the function level __name__. So how could I refer to the function object per se, in the body of the function itself? From johnjsal at NOSPAMgmail.com Fri Mar 31 18:39:43 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 31 Mar 2006 18:39:43 -0500 Subject: a simple regex question Message-ID: <442dbe42$0$11647$c3e8da3@news.astraweb.com> Ok, I'm stuck on another Python challenge question. Apparently what you have to do is search through a huge group of characters and find a single lowercase character that has exactly three uppercase characters on either side of it. Here's what I have so far: pattern = '([a-z][A-Z]{3}[a-z][A-Z]{3}[a-z])+' print re.search(pattern, mess).groups() Not sure if 'groups' is necessary or not. Anyway, this returns one matching string, but when I put this letter in as the solution to the problem, I get a message saying "yes, but there are more", so assuming this means that there is more than one character with three caps on either side, is my RE written correctly to find them all? I didn't have the parentheses or + sign at first, but I added them to find all the possible matches, but still only one comes up. Thanks. From anagappan at novell.com Wed Mar 29 12:50:27 2006 From: anagappan at novell.com (A Nagappan) Date: Wed, 29 Mar 2006 12:50:27 -0500 Subject: LDTP 0.4.0 released !!! Message-ID: <442B163B0200004400005175@mcclure.wal.novell.com> Issue VII - 29 March 2006 Welcome to the seventh issue of LDTP Newsletter! We are now celebrating our 0.4.0 release. This release features exhaustive list of bug fixes. LDTP is now stable than ever before.Useful references have been included at the end of this article for those who wish to hack/use LDTP. About LDTP Linux Desktop Testing Project is aimed at producing high quality test automation framework and cutting-edge tools that can be used to test Linux Desktop and improve it. It uses the "Accessibility" libraries to poke through the application's user interface. Thanks to the Accessibility team. LDTP automation framework helps in automatically executing test cases for verifying the functionality of the software being tested. This release includes.... * Refined object search from the appmap table * Data XML are now transmitted and received with in CDATA * Reimplemented getwindowlist, getobjectlist, getobjectinfo,getobjectproperty * Memory leak fixed - Freed memory resources when client disconnects And now take a deep breath and go through the exhaustive list of bug fixes which makes this version of LDTP the most stable of the lot. A special thanks to Patrick from Sun Microsystems who has actively hacked LDTP and helped us identify and resolve many issues. * client-handler.c (add_item_to_list): A common function to generate XML object list. * client-handler.c (send_response): If data sent in chunks from server to client, then the peek code in client was not able to continue reading the next chunk as the recv with peek option always returns the first chunk. * client-handler.c (handle_request): Implemented getwindowlist, getobjectlist, getobjectinfo, getobjectproperty. Modified initappmap to get the file name from gslist only once. Memory leak fixed - Freed memory resources when client disconnects. * ldtp.c (ldtp_print): Indentation * ldtp-appmap.c (remove_appmap_entries): Memory leak fixed - Freed memory resources when client disconnects. * ldtp-appmap.c (search_obj_after_stripping_space): Added new function to search for an object after stripping spaces. * ldtp-appmap.c (add_child_attributes): Modified it as static function. * ldtp-appmap.c (ldtp_appmap_free): If appmap is not NULL then only traverse the hash table. To avoid a critical warning. * ldtp-appmap.c (search_label_based): Modified the logic to check for label or label_by and also, if under score is in value, then remove it and then look for the match. * ldtp-command.c (ldtp_command_init_command_table): Added getwindowlist, getobjectlist, getobjectinfo, getobjectproperty commands to the list of commands. * ldtp-error.c (ldtp_error_get_error_message): Added new error messages. * ldtp-gui.c (ldtp_gui_get_gui_handle): If appmap is not initialized, then try to initialize it by updating the window handle. * ldtp-gui.c (update_cur_window_appmap_handle): Checked for argument NULL to avoid crash. * ldtp-logger.c (ldtp_log): vprintf also will be printed iff LDTP_DEBUG option is enabled. * ldtp-request.c (ldtp_request_fill_request): When XML packet is NULL don't process further, which avoids a crash. * ldtp-utils.c (escape_character): Modified function name escape_under_score to escape_character and also added one parameter to make this function a generic one. Check if argument is not NULL then continue else return immediately. * remap.c (get_keybinding, filter_appmap_data, get_object_info, add_appmap_data): Checked for NULL arguments to avoid crash. * remap.c (accessible_object_handle): Avoided memory fragmentation as the same data is allocated multiple times. LDTP 0.4.0 is available is rpm package. Thanks to Damien Carbery and Dave Lin of Sun Microsystems for creating LDTP packages for solaris. LDTP makes news An article has been published in the German journal "Software-Wydawnictwo Sp. z o.o" about LDTP. If your in Germany, dont let this oppurtunity slip away. Grab a copy and check out the simple article which covers the length and breadth of LDTP. Downloads... You can download the latest version of LDTP from http://ldtp.freedesktop.org/wiki/Downloads LDTP is available as rpm package. LDTP is also available as deb package for Debian and Ubuntu distributions. Thanks to Casanova (prashmohan at gmail.com) for the providing the same. For a step by step instruction on setting up LDTP please refer http://ldtp.freedesktop.org/wiki/How_20to_20setup_20pyldtp_20in_20GNU_2fLinux_20environment References For detailed information on LDTP framework and latest updates visit http://ldtp.freedesktop.org All the published newsletters including the current one can be downloaded from http://ldtp.freedesktop.org/wiki/Newsletters For release notes of every release including the current one please refer http://ldtp.freedesktop.org/wiki/Release_20Notes For information on various APIs in LDTP including those added for this release can be got from http://ldtp.freedesktop.org/wiki/API_20Reference To subscribe to LDTP mailing lists, visit http://ldtp.freedesktop.org/wiki/Mailing_20list IRC Channel - #ldtp on irc.freenode.net For suggestions to improve this newsletter, please write to jpremkumar at novell.com Nagappan A Linux Desktop Testing Project - http://ldtp.freedesktop.org http://nagappanal.blogspot.com From duncan.booth at invalid.invalid Wed Mar 1 13:45:52 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Mar 2006 18:45:52 GMT Subject: Use empty string for self References: <1141170846.619246.163470@t39g2000cwt.googlegroups.com> <120a94q7qnhb97@corp.supernews.com> <120bi38s9ms3i34@corp.supernews.com> Message-ID: John Salerno wrote: >> The two calls are equivalent. > > can you also say instance.mymethod(instance, 1, 2) ? Only if mymethod is defined to take all 4 arguments you just passed to it. From skip at pobox.com Tue Mar 21 12:32:24 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 21 Mar 2006 11:32:24 -0600 Subject: datetime iso8601 string input In-Reply-To: References: <1140714826.044272.253460@t39g2000cwt.googlegroups.com> Message-ID: <17440.14504.55882.738781@montanaro.dyndns.org> aurora> I agree. I just keep rewriting the parse method again and again. aurora> def parse_iso8601_date(s): aurora> """ Parse date in iso8601 format e.g. 2003-09-15T10:34:54 and aurora> returns a datetime object. aurora> """ ... Why not dt = datetime.datetime(*time.strptime(s, "%Y-%m-%dT%H:%M:%S")[0:6]) ? Skip From fuzzyman at gmail.com Fri Mar 24 11:50:15 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Mar 2006 08:50:15 -0800 Subject: What's The Best Editor for python In-Reply-To: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> References: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> Message-ID: <1143219015.213624.190170@j33g2000cwa.googlegroups.com> PythonStudent wrote: > Hi, > Can one of you say to me what's the best editor for editing the python > programs ( for linux or windows ), and if you can send it to me to the > adresse Ahcheriet at gmail.com > `SPE `_ :-) Fuzzyman http://www.voidspace.org.uk/python/index.shtml > > > Thanks From har7yys at hotmail.com Thu Mar 2 09:56:41 2006 From: har7yys at hotmail.com (Glurt Wuntal) Date: 2 Mar 2006 14:56:41 -0000 Subject: Write a GUI for a python script? Message-ID: I am a newbie with Python. It's a great language, but I would like to be able to present a simple gui menu for some of my scripts; something better than using 'raw_input' prompts. Any recommendations for a program that will allow me to create the gui screens? Something useable in Linux. thanks. From jimmy at retzlaff.com Mon Mar 20 07:24:47 2006 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Mon, 20 Mar 2006 04:24:47 -0800 Subject: py2exe 0.6.5 released Message-ID: py2exe 0.6.5 released ===================== py2exe is a Python distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation. Console and Windows (GUI) applications, Windows NT services, exe and dll COM servers are supported. Changes in 0.6.5: * Fixed modulefinder / mf related bugs introduced in 0.6.4. This will be most evident when working with things like win32com.shell and xml.xpath. * Files no longer keep read-only attributes when they are copied as this was causing problems with the copying of some MS DLLs. Changes in 0.6.4: * New skip-archive option which copies the Python bytecode files directly into the dist directory and subdirectories - no archive is used. * An experimental new custom-boot-script option which allows a boot script to be specified (e.g., --custom-boot-script=cbs.py) which can do things like installing a customized stdout blackhole. See py2exe's boot_common.py for examples of what can be done. The custom boot script is executed during startup of the executable immediately after boot_common.py is executed. * Thomas Heller's performance improvements for finding needed modules. * Mark Hammond's fix for thread-state errors when a py2exe created executable tries to use a py2exe created COM DLL. Changes in 0.6.3: * First release assembled by py2exe's new maintainer, Jimmy Retzlaff. Code changes in this release are from Thomas Heller and Gordon Scott. * The dll-excludes option is now available on the command line. It was only possible to specify that in the options argument to the setup function before. The dll-excludes option can now be used to filter out dlls like msvcr71.dll or even w9xpopen.exe. * Fix from Gordon Scott: py2exe crashed copying extension modules in packages. Changes in 0.6.2: * Several important bugfixes: - bundled extensions in packages did not work correctly, this made the wxPython single-file sample fail with newer wxPython versions. - occasionally dlls/pyds were loaded twice, with very strange effects. - the source distribution was not complete. - it is now possible to build a debug version of py2exe. Changes in 0.6.1: * py2exe can now bundle binary extensions and dlls into the library-archive or the executable itself. This allows to finally build real single-file executables. The bundled dlls and pyds are loaded at runtime by some special code that emulates the Windows LoadLibrary function - they are never unpacked to the file system. This part of the code is distributed under the MPL 1.1, so this license is now pulled in by py2exe. * By default py2exe now includes the codecs module and the encodings package. * Several other fixes. Homepage: Download from the usual location: Enjoy, Jimmy From grante at visi.com Wed Mar 8 23:45:03 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 09 Mar 2006 04:45:03 -0000 Subject: advice on this little script References: <2bSdncqWK7aJN5LZRVn-vA@rcn.net> <120vb889343kd1@corp.supernews.com> Message-ID: <120vcmf3fgdo7d8@corp.supernews.com> On 2006-03-09, John Salerno wrote: > Grant Edwards wrote: >> On 2006-03-09, John Salerno wrote: >> >>> from time import sleep >>> >>> minutes = input('Enter the number of minutes to wait: ') >>> >>> for x in range(minutes): >>> sleep(1.0) >>> minutes -= 1 >>> print minutes, 'minutes remaining.' >> >> for x in range(minutes,0,-1): >> sleep(60.0) >> print minutes, 'minutes remaining' > > Nice! Cross off another line! I feel like Hemingway. :) Was he the one who once apologized to his editor for a story being so long because he was in a hurry and didn't have time to make it shorter? -- Grant Edwards grante Yow! NEWARK has been at REZONED!! DES MOINES has visi.com been REZONED!! From daconti.mail at gmail.com Mon Mar 27 17:06:06 2006 From: daconti.mail at gmail.com (DrConti) Date: 27 Mar 2006 14:06:06 -0800 Subject: object references References: <1143351204.139672.36490@i39g2000cwa.googlegroups.com> <4426e4cf$0$11336$636a55ce@news.free.fr> Message-ID: <1143497166.915617.196650@v46g2000cwv.googlegroups.com> Hi Bruno, hi folks! thank you very much for your advices. I didn't know about the property function. I learned also quite a lot now about "references". Ok everything is a reference but you can't get a reference of a reference... I saw a lot of variations on how to solve this problem, but I find actually that the "property approach" is the most natural of all. Basically the idea there is that you build up this list of class attributes not by storing a reference to a class attribute (which seem to be impossible), but you just store on each element of the list one method (pardon a reference to..) to get the associated class attribute. Sorry for the UnPythonity. I used to be a CamelRider. But not very longtime ago I left the Camel in the Desert, because I met the Snake.... Regs, Davide. From chemosh at kampinada.de Thu Mar 16 06:14:02 2006 From: chemosh at kampinada.de (Kai Schulte) Date: Thu, 16 Mar 2006 11:14:02 -0000 Subject: mod_python installation In-Reply-To: <1138630887.702201.124100@g43g2000cwa.googlegroups.com> References: <1138622000.794944.173020@g47g2000cwa.googlegroups.com> <1138630887.702201.124100@g43g2000cwa.googlegroups.com> Message-ID: <200601302146.03160.chemosh@kampinada.de> The Debian stable package tree has only libapache2-mod-python2.3 (3.1.3-3). You can look at http://packages.debian.org/stable/python/ for a detailed list. If you really want to use python2.4 you can either try to use the ubuntu package (http://packages.ubuntu.org.cn/breezy/python/libapache2-mod-python2.4) but I would not recommend it, since it could break your system. Or you could search a backport, may be there is one. Am Montag, 30. Januar 2006 15:21 schrieb Ravi Teja: > I have Ubuntu which uses the Debian package tree. > I see libapache2-mod-python2.4 with "apt-cache search mod_python" > Perhaps you don't have all the repositories enabled? Ubuntu uses mostly the debian testing/unstable or even experimental package tree plus its own package tree, so there are a few packages only available to Ubuntu. From johnjsal at NOSPAMgmail.com Fri Mar 3 12:59:57 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 03 Mar 2006 17:59:57 GMT Subject: Does '#hash' mean anything in IDLE? In-Reply-To: <1141394786.531934.134920@t39g2000cwt.googlegroups.com> References: <1141331534.634181.275880@p10g2000cwp.googlegroups.com> <1141332159.625375.40540@e56g2000cwe.googlegroups.com> <3TINf.1719$No6.40137@news.tufts.edu> <1141394786.531934.134920@t39g2000cwt.googlegroups.com> Message-ID: John Coleman wrote: > How do you like Python so far? So far I'm pretty impressed with its simplicity. Seems like anything I write in 5+ lines can be condensed to one line! :) Coming from C#, it was just such a surprise to see how much easier it is to do things in Python. I'm also interested in the dictionary object, simply because it's something a little different than I'm used to, and very convenient to have built-in. From steve at REMOVETHIScyber.com.au Thu Mar 9 07:13:17 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 09 Mar 2006 23:13:17 +1100 Subject: Simple questions on use of objects (probably faq) References: <440ed33e$0$8002$636a55ce@news.free.fr> <440ff09d$0$20266$626a54ce@news.free.fr> Message-ID: On Thu, 09 Mar 2006 11:54:11 +0100, Brian Elmegaard wrote: >> What is "going wrong" exactly ? > > def _add_instance(cls, instance): > _add_instance=classmethod(_add_instance) > cls._instances.append(instance) > > gives me: > d:/DTU/80494 $ python.exe ooo.py > Traceback (most recent call last): > File "ooo.py", line 36, in ? > Foo(value) > File "ooo.py", line 6, in __init__ > self._add_instance(self) > File "ooo.py", line 9, in _add_instance > _add_instance=classmethod(_add_instance) > UnboundLocalError: local variable '_add_instance' referenced before assignment This isn't a bug in version 2.3. It is a bug in your code. Follow the code at runtime when you call the method: Calling x._add_instance(foo) calls the _add_instance method with arguments x.__class__ and foo. The first instruction that gets executed is: _add_instance=classmethod(_add_instance) but _add_instance doesn't exist inside the method's local scope, so you get an UnboundLocalError exception. What you probably think you want is something like this: class Foo: _instances = [] def _add_instance(cls, instance): cls._instances.append(instance) _add_instances = classmethod(_add_instances) I say "think you want" because I don't know what problem you are trying to solve with this messy, self-referential, piece of code. If you could explain what your goal is, there is probably a better way of reaching it. -- Steven. From mystilleef at gmail.com Mon Mar 6 11:43:22 2006 From: mystilleef at gmail.com (Mystilleef) Date: 6 Mar 2006 08:43:22 -0800 Subject: Why I chose Python over Ruby References: <1141573450.667103.8930@z34g2000cwc.googlegroups.com> Message-ID: <1141663402.500569.261460@i39g2000cwa.googlegroups.com> Simple, clarity! Ruby reads like Perl's younger cousin. From juho.schultz at helsinki.fi Fri Mar 10 09:43:15 2006 From: juho.schultz at helsinki.fi (Juho Schultz) Date: Fri, 10 Mar 2006 16:43:15 +0200 Subject: File Permissions In-Reply-To: <1142000418.480825.247970@v46g2000cwv.googlegroups.com> References: <1142000418.480825.247970@v46g2000cwv.googlegroups.com> Message-ID: VJ wrote: > Hi All > > Basically i want to write into a file .If the permissions are not there > then print a error message. > How do i achive this ??? > > Thanks, > VJ > One way would be a try-except block, and leave the permission checking error message generation, etc. to the operating system. try: outfile = file(outfilename,"w") except IOError, errormsg print "Could not write to file %s: %s" % (outfilename, errormsg) From steven.bethard at gmail.com Fri Mar 3 12:12:40 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 03 Mar 2006 10:12:40 -0700 Subject: PythonWin: any way to delete all objects without exiting and without doing it with "del"? In-Reply-To: <1141377705.762385.224680@i40g2000cwc.googlegroups.com> References: <1141250922.615071.68700@i39g2000cwa.googlegroups.com> <87wtfd7r4c.fsf@voodoo.myself> <1141293267.991614.156170@i39g2000cwa.googlegroups.com> <1141377705.762385.224680@i40g2000cwc.googlegroups.com> Message-ID: dananrg at yahoo.com wrote: > Steven, does your technique fix my problem? Would that delete the > objects I've created within a program if I suffix my code with it? I'm not certain I understand your problem, but I think so. Give it a try. STeVe From nogradi at gmail.com Sun Mar 19 12:31:38 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 19 Mar 2006 18:31:38 +0100 Subject: [ann] markup.py - HTML/XML generator Message-ID: <5f56302b0603190931h23bac3d6x5691ec13b970dceb@mail.gmail.com> Just in case the thought of not having a millionth implementation of a HTML/XML generator for Python makes the world as we know it a miserable place, well then your suffering might be over soon since exactly the one millionth implementation is out. You can download markup.py from http://markup.sourceforget.net/ Oh, and the code is in the public domain. From preved.rly at gmail.com Thu Mar 30 09:38:43 2006 From: preved.rly at gmail.com (preved.rly at gmail.com) Date: 30 Mar 2006 06:38:43 -0800 Subject: Countdown from 2 minutes - how? References: <1143725108.307128.16110@v46g2000cwv.googlegroups.com> Message-ID: <1143729523.889448.320130@v46g2000cwv.googlegroups.com> #!/bin/env python # countdown.py import time import doctest def countdown( time_in_minutes): """ >>> import countdown >>> countdown.countdown(0.1) # doctest:+ELLIPSIS 6 5 ... 1 Time is up """ for i in xrange(int(time_in_minutes * 60 + 0.5), 0, -1): print i time.sleep(1) print 'Time is up' if __name__=='__main__': doctest.testmod() From vvikram at gmail.com Thu Mar 30 06:58:19 2006 From: vvikram at gmail.com (vvikram at gmail.com) Date: 30 Mar 2006 03:58:19 -0800 Subject: re.I slowness Message-ID: <1143719899.018571.41330@u72g2000cwu.googlegroups.com> We process a lot of messages in a file based on some regex pattern(s) we have in a db. If I compile the regex using re.I, the processing time is substantially more than if I don't i.e using re.I is slow. However, more surprisingly, if we do something on the lines of : s = s = s.lower() t = dict([(k, '[%s%s]' % (k, k.upper())) for k in string.ascii_lowercase]) for k in t: s = s.replace(k, t[k]) re.compile(s) ...... its much better than using plainly re.I. So the qns are: a) Why is re.I so slow in general? b) What is the underlying implementation used and what is wrong, if any, with above method and why is it not used instead? Thanks Vikram From prettyboy988-google at yahoo.com Fri Mar 3 04:03:38 2006 From: prettyboy988-google at yahoo.com (P Boy) Date: 3 Mar 2006 01:03:38 -0800 Subject: slicing the end of a string in a list In-Reply-To: References: <1141374847.159701.29680@i40g2000cwc.googlegroups.com> Message-ID: <1141376618.133583.103580@i39g2000cwa.googlegroups.com> I had some issues while ago trying to open a large binary file. Anyway, from file() man page: If mode is omitted, it defaults to 'r'. When opening a binary file, you should append 'b' to the mode value for improved portability. (It's useful even on systems which don't treat binary and text files differently, where it serves as documentation.) The optional bufsize argument specifies the file's desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used.2.3 From steve at REMOVEMEcyber.com.au Wed Mar 8 18:59:29 2006 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 09 Mar 2006 10:59:29 +1100 Subject: help References: Message-ID: <440F6FE1.3050100@REMOVEMEcyber.com.au> Steve Holden wrote: > Alexander wrote: > >> hi, my name is alexander. i'm from indonesia >> i wanna ask, is there Pygoogle with GUI? because i've got assignment >> from my teacher to make an user interface for Pygoogle. if there's a >> Pygoogle with GUI, can u tell me where to find it. >> > So "make" now means "pull from the Internet"? Huh! When I was in school, we needed to intimidate the brainy kid with glasses to plagarise our assignments. We didn't have strangers half-way across the world offering to do our work for us for free. Kids today have it easy. -- Steven. From alainpoint at yahoo.fr Tue Mar 14 16:33:01 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 14 Mar 2006 13:33:01 -0800 Subject: Is this possible in Python? SOLUTION FOUND In-Reply-To: <1142360116.660443.67380@i40g2000cwc.googlegroups.com> References: <1142238871.199749.243470@p10g2000cwp.googlegroups.com> <1142282467.270698.142780@p10g2000cwp.googlegroups.com> <1142331474.355167.20970@i40g2000cwc.googlegroups.com> <1142340220.720530.27590@p10g2000cwp.googlegroups.com> <1142360116.660443.67380@i40g2000cwc.googlegroups.com> Message-ID: <1142371981.816264.113390@v46g2000cwv.googlegroups.com> Kay Schluehr wrote: > alainpoint at yahoo.fr wrote: > > jalanb wrote: > > > You might like the version here: > > > http://www.jorendorff.com/toys/out.html > > > > > > Especially the "need to know" presentation, which is cute > > > > > > -- > > > Alan > > > http://aivipi.blogspot.com > > > > Thank you for the tip. > > Meanwhile, I found a shorter solution to my problem: > > def magic(arg): > > import inspect > > return inspect.stack()[1][4][0].split("magic")[-1][1:-1] > > > > assert magic(3+4)=="3+4" > > > > Alain > > Does it? Using your function I keep an assertion error. Storing the > return value of magic()in a variable s I receive the following result: > > def magic(arg): > import inspect > return inspect.stack()[1][4][0].split("magic")[-1][1:-1] > > s = magic(3+4) # magic line > > >>> s > 'lin' > > > BTW grepping the stack will likely cause context sensitive results. > > Kay This is no production-ready code, just a proof of concept. Adding 3 or 4 lines would make it more robust. Just hope someone else will benefit from this discussion. Alain From shandy.b at gmail.com Thu Mar 2 16:01:45 2006 From: shandy.b at gmail.com (shandy.b at gmail.com) Date: 2 Mar 2006 13:01:45 -0800 Subject: do design patterns still apply with Python? References: <8SINf.1718$No6.40137@news.tufts.edu> Message-ID: <1141333305.284973.54620@z34g2000cwc.googlegroups.com> Hi John. Design patterns aren't tied to any specific implementation so they should apply to any language. You might find that they can even apply to solution domains outside of computer science. Implementation details will usually differ between languages. But the implementation can also be different using the same language. For example, you can use Java to implement the Model View Controller design pattern when writing a web site or when writing a database engine -- the implementation will be very different, but both will be MVC. In python, you might find it more natural to do design patterns in a completely different way than they're implemented in Java. For example, I've heard of using the Singleton pattern in python by just implementing it as a module, no classes necessary. sjbrown From steve at REMOVETHIScyber.com.au Mon Mar 6 07:14:57 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 06 Mar 2006 23:14:57 +1100 Subject: raw strings and \ References: <1141548565.145199.145910@e56g2000cwe.googlegroups.com> <1141576051.081203.318010@e56g2000cwe.googlegroups.com> <1hbpy3y.23h9u0zn7y7zN%aleaxit@yahoo.com> <1141580623.066639.51160@u72g2000cwu.googlegroups.com> <1hbq3fx.2idn1u1cei6j0N%aleaxit@yahoo.com> <1141616827.542848.59870@j52g2000cwj.googlegroups.com> Message-ID: Almost off-topic. Well, okay, completely off-topic. On Sun, 05 Mar 2006 19:47:07 -0800, plahey wrote: > I would say that a foolish anything is something to avoid. I don't > think that anyone would claim that inconsistency is a virtue in a > computer language (or in anything else for that matter). Inconsistency can be a virtue whenever predictability is a vice. Imagine, for example, that Fred and Bill are negotiating over something (say, Fred wants to buy Bill's house). If Fred is predictable, then Bill can work out just how high Fred is willing to pay, and refuse to accept a penny less. In other words, if you are too consistent, people will learn to take advantage of that consistency to get the most from you for the least in return. On the other hand, if Fred is unpredictable -- that is, inconsistent -- it is much harder to predict his behaviour, and Bill will be more cautious and more likely to settle for a lower offer. Think about hostile negotiations. If people know exactly how far they can push you before you will get mad, they will push right to the edge. But if they don't know where that edge lies, if they are uncertain how you will react ("if I demand the Sudetenland, will he break off negotiations and launch a preemptive attack?"), they will be more cautious, less demanding, more open to compromise. Cognitive scientists believe that the benefits of unpredictability and inconsistency are behind the evolution of such irrational emotions as jealousy and rage. In that sense, their very irrationality is what makes them rational. -- Steven. From steve at REMOVEMEcyber.com.au Wed Mar 1 03:31:28 2006 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Wed, 01 Mar 2006 19:31:28 +1100 Subject: Make staticmethod objects callable? References: Message-ID: <44055BE0.8030409@REMOVEMEcyber.com.au> Nicolas Fleury wrote: > Hi everyone, > I was wondering if it would make sense to make staticmethod objects > callable, so that the following code would work: This is one of the more unintuitive areas of Python, with side effects and different behaviour depending on whether code is called inside or outside a class: >>> class Parrot: ... def speak(): ... return "dead parrot" ... speak = staticmethod(speak) ... def playdead(): ... return "still dead" ... >>> type(Parrot.speak) >>> type(Parrot.playdead) So, based on this evidence, staticmethod() converts an instance method into an ordinary function. Parrot.speak certainly behaves like an ordinary function. >>> callable(Parrot.speak) True >>> Parrot.speak() 'dead parrot' But now try to do the same outside of a class: >>> f = staticmethod(Parrot.playdead) >>> type(f) f is not a function? >>> Parrot.playdead = staticmethod(Parrot.playdead) >>> type(Parrot.playdead) So, based on this evidence, staticmethod() inside a class definition converts instance methods to functions. Outside a class definition, staticmethod() does one of two things: it either converts an instance method to a static method, or if the output is assigned to a class attribute, it leaves it as an instance method. Hmmm. > class A: > @staticmethod > def foo(): pass > bar = foo() Here is a work around: >>> class A: ... def foo(): return "foo foo foo" ... foo = staticmethod(foo) ... def __init__(self): ... if not hasattr(self.__class__, "bar"): ... self.__class__.bar = self.foo() ... >>> dir(A) ['__doc__', '__init__', '__module__', 'foo'] >>> a = A() >>> dir(A) ['__doc__', '__init__', '__module__', 'bar', 'foo'] >>> a.foo() 'foo foo foo' >>> a.bar 'foo foo foo' Here is a more interesting example: >>> class B: ... def foo(): ... return lambda x: x+1 ... foo = staticmethod(foo) ... def __init__(self): ... if not hasattr(self.__class__, "bar"): ... self.__class__.bar = \ ... staticmethod(self.foo()) ... >>> dir(B) ['__doc__', '__init__', '__module__', 'foo'] >>> b = B() >>> dir(B) ['__doc__', '__init__', '__module__', 'bar', 'foo'] >>> b.foo() at 0xb7f70c6c> >>> b.bar at 0xb7f70c34> >>> b.bar(3) 4 Hope this helps. -- Steven. From phpbird at gmail.com Wed Mar 15 11:58:46 2006 From: phpbird at gmail.com (JuHui) Date: 15 Mar 2006 08:58:46 -0800 Subject: how to get 20000 html pages content quickly from one server? In-Reply-To: <1142441572.689735.273320@j33g2000cwa.googlegroups.com> References: <1142439755.840346.181060@p10g2000cwp.googlegroups.com> <1142441572.689735.273320@j33g2000cwa.googlegroups.com> Message-ID: <1142441926.525376.312030@i40g2000cwc.googlegroups.com> in fact, I want to do a script to get news on others site. I must use script get the content and analyze the html code, where is the title, where is the body.... so, I can't ask permission, use wget and "Physically remove the harddrive and reinstall it locally" :) From Jeff.Quandt at bhmi.com Fri Mar 3 10:06:36 2006 From: Jeff.Quandt at bhmi.com (Jeff Quandt) Date: Fri, 3 Mar 2006 09:06:36 -0600 Subject: Write a GUI for a python script? Message-ID: Glurt Wuntal (02.03.2006 15:56): > I am a newbie with Python. It's a great language, but I would like to be > able to present a simple gui menu for some of my scripts; something better > than using 'raw_input' prompts. > Another option is to use Jython, which allows you access to Java as well. So, you can can write the procedural aspects in Python and add GUI support from Java. You're probably looking for Tkinter, but I thought I'd throw the Jython option out there. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: From sathyaish at gmail.com Mon Mar 13 05:34:13 2006 From: sathyaish at gmail.com (Sathyaish) Date: 13 Mar 2006 02:34:13 -0800 Subject: Environmental Variables Message-ID: <1142246053.485766.41280@i39g2000cwa.googlegroups.com> In which physical file are the python environmental variables located? I know I can access them using the: os.environ.get('PYTHONSTARTUP') or os.environ.get('PYTHONPATH') to get their values. But out of the program, if I need to look at them and alter their values, where do I find them? Are they the OS environmental variables as I suspect? If they are, then I'll find them with the other OS environ variables in My Computer->System->Properties->Advanced->Environmental Variables. But I checked that place and did not find any default values for them. From gslindstrom at gmail.com Wed Mar 29 11:05:00 2006 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Wed, 29 Mar 2006 10:05:00 -0600 Subject: Central Arkansas Python Users Group Message-ID: <57aa55060603290805q3ba07c59q37ade4c66091e20c@mail.gmail.com> At PyCon I met a handful of programmers from the Little Rock area. Are there enough of us with any interest in forming a Central Arkansas Python Users Group? For others of you that have started user groups, how do you get the word out, especially in an area where Python coders are difficult to find (but I *know* they're out there!). If you're interested, email me gslindstrom at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at ucla.edu Wed Mar 1 00:13:28 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 28 Feb 2006 21:13:28 -0800 Subject: type = "instance" instead of "dict" In-Reply-To: References: <1141069989.763239.191140@u72g2000cwu.googlegroups.com> Message-ID: Mel Wilson wrote: > James Stroud wrote: > >> Fredrik Lundh wrote: >> >>> James Stroud wrote: >>> >>> >>>> Perhaps you did not know that you can inheret directly from dict, which >>>> is the same as {}. For instance: >>>> >>>> class Dict({}): >>>> pass >> >> >> >> I must have been hallucinating. I swear I did this before and it >> worked just like class Dict(dict). Since it doesn't read as well, I've >> never used it. >> >>> > > class D (type({})): > '''This derivative of dictionary works.''' > > Could that have been it? > > Mel. This rings a bell. It was a couple of years ago, so the "type" must have faded from my already murky memory. James From mandelin at cs.berkeley.edu Tue Mar 28 13:56:53 2006 From: mandelin at cs.berkeley.edu (Dave Mandelin) Date: 28 Mar 2006 10:56:53 -0800 Subject: dir_util.copy_tree call References: <1143569102.968495.265110@t31g2000cwb.googlegroups.com> Message-ID: <1143572213.183420.85990@v46g2000cwv.googlegroups.com> In IDLE, by default the working directory for the interactive prompt is the working directory for IDLE itself. The working directory for running a module is the directory the module is stored in. In your script, use absolute paths or set the -- Want to play tabletop RPGs over the internet? Check out Koboldsoft RPZen: http://www.koboldsoft.comcwd. From danmcleran at yahoo.com Tue Mar 14 12:44:03 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 14 Mar 2006 09:44:03 -0800 Subject: Python Debugger / IDE ?? In-Reply-To: <1142357338.313046.139060@i39g2000cwa.googlegroups.com> References: <1142357338.313046.139060@i39g2000cwa.googlegroups.com> Message-ID: <1142358243.640532.278480@z34g2000cwc.googlegroups.com> >Is there any editor or IDE in Python (either Windows or Linux) which >has very good debugging facilites like MS VisualStudio has or something >like that. I've been using Eclipse with PyDev and am very happy with it. From bobrien18 at yahoo.com Mon Mar 6 12:01:38 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 6 Mar 2006 09:01:38 -0800 Subject: Need help initializing a list or tuple. Message-ID: <1141664498.539402.43160@e56g2000cwe.googlegroups.com> I need a matrix of 256 x 256 unsigned short values... The matrix can be implemented as a list of lists or a tuple... So for example: [[1][2][3], [4][5][6], [7][8][9]] or ((1,2,3),(4,5,6), (7,8,9)) This is what I have so far but its not working... a = [][] for i in range(0,256): for j in range(0,256): a[i][j] = i**2 From eoinrogers at gmail.com Sat Mar 18 09:43:11 2006 From: eoinrogers at gmail.com (Byte) Date: 18 Mar 2006 06:43:11 -0800 Subject: Importing an output from another function In-Reply-To: References: <1142626528.204581.179350@v46g2000cwv.googlegroups.com> <1142627019.614450.250540@i40g2000cwc.googlegroups.com> <1142628076.041352.320560@i40g2000cwc.googlegroups.com> <1142629118.886810.251200@u72g2000cwu.googlegroups.com> Message-ID: <1142692991.286960.54270@i39g2000cwa.googlegroups.com> "Try this (I think its called "argument expansion", but I really don't know what its called, so I can't point you to docs):" This works, thanks. But how acn I get rid of the ugly surrounding brackets and commas? e.g. If the scripts overall output was (('B', 'C'),), how to change it to just B C? From dinko.tenev at gmail.com Wed Mar 22 05:24:12 2006 From: dinko.tenev at gmail.com (Dinko Tenev) Date: 22 Mar 2006 02:24:12 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1142589945.078364.32870@i39g2000cwa.googlegroups.com> <1142599685.186209.177630@j33g2000cwa.googlegroups.com> <1142647977.696295.124650@i40g2000cwc.googlegroups.com> <87u09w9qsj.fsf@shiva.mad.wi.charter.com> <1142847498.862462.57340@i40g2000cwc.googlegroups.com> <1142985094.180466.306460@i40g2000cwc.googlegroups.com> Message-ID: <1143023052.390444.32380@u72g2000cwu.googlegroups.com> funkyj wrote: > How about the other iterator characteristics? > > when there is a huge solution space can I ask the prolog version to > give me the first 1000 solutions? Geoffrey's post above offers one way to do this from within a REPL. Within a program, as soon as you accept a solution, you're potentially out of the "loop" (it is possible to use cut (!) to make this certain.) > The next 1000 solutions (i.e. 1000 - 1999)? I am not quite sure how exactly you propose to do this in e.g. Python, but if you mean to enumerate and skip over the first 1000 and then continue with the rest, yes, this is also possible. > If you can do that then it would appear that generators have no > advantage over your prolog solution. To be fair, the Python implementation has one significant advantage -- it offers reduced runtime complexity for quite a number of practical cases (of course, this improvement is achievable in Prolog too,) though I'm still inclined to think that it can be made to run in exponential time. Also, my Prolog version is non-compliant in that it treats a wildcard as matching a single position, rather than matching any sequence. Geoffrey's implementation does the right thing though. Cheers, Dinko From diffuser78 at gmail.com Thu Mar 30 18:21:38 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 30 Mar 2006 15:21:38 -0800 Subject: how to comment lot of lines in python Message-ID: <1143760897.940841.285300@i39g2000cwa.googlegroups.com> Like in C we comment like /* Bunch of lines of code */ Should we use docstring """ """ Or there is something else too ?? Every help is appreciated. Thanks From R.Brodie at rl.ac.uk Thu Mar 30 09:48:54 2006 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 30 Mar 2006 15:48:54 +0100 Subject: How to determine an object is "scriptable" References: <1143726903.153135.317880@j33g2000cwa.googlegroups.com> <1143728317.535829.121950@i39g2000cwa.googlegroups.com> Message-ID: "abcd" wrote in message news:1143728317.535829.121950 at i39g2000cwa.googlegroups.com... > doesn't seem to be a builtin function or module...or is that just your > definition of subscriptable? Yes, I figured you were just confused. You were using the wrong words, after all. From riklaunim at gmail.com Sat Mar 25 08:27:17 2006 From: riklaunim at gmail.com (=?ISO-8859-2?Q?piotr_mali=F1ski?=) Date: Sat, 25 Mar 2006 13:27:17 +0000 Subject: MyghtyBoard 0.0.1 Message-ID: <1f7f7cf70603250527x63de734as@mail.gmail.com> MyghtyBoard 0.0.1 alfa have been released. It's a forum script written in python/myghty/hk_classes. Download: http://sourceforge.net/project/showfiles.php?group_id=163611&package_id=185021&release_id=404570 Few old screens: http://www.fotosik.pl/pokaz_obrazek/q0pq9tc1i6aphwc4.html http://www.fotosik.pl/pokaz_obrazek/4xdrt560ove5i0gf.html http://www.fotosik.pl/pokaz_obrazek/tf2tqifsog43eiuv.html Requirements: - Python :) - Myghty - http://www.myghty.org/ - hk_classes python module - http://hk-classes.sourceforge.net/tiki-page.php?pageName=Description - MySQL database Installation howto is in the readme. All comments and suggestions are welcome. From apardon at forel.vub.ac.be Mon Mar 6 05:08:17 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 Mar 2006 10:08:17 GMT Subject: Suggesting the use of StandardError as base of error Exceptions. Message-ID: In a number of cases I have a program that looks like the following. for case in all_cases: try: treat(case) except Exception, ErrInfo: generate_traceback() The idea is to get as much information as possible when something goes wrong but at the same time treat as many cases as possible. Then one day things broke. The reason was that in some circumstances treat would decide that things were beyond control and called sys.exit However sys.exit doesn't return to the O.S. immediately but raises SystemExit, which was caugth by the code and the loop continued. I then took a look at http://docs.python.org/lib/module-exceptions.html which describes the exception heirarchy as follows: Exception +-- SystemExit +-- StopIteration +-- StandardError | + | + All kind of error exceptions | + +---Warning + + All kind of warnings + and came to the conclusion, that it would be better to write my code as follows: for case in all_cases: try: treat(case) except StandardError, ErrInfo: generate_traceback() Unfortunatly this doesn't work either because a lot of the error exceptions in the stdlib (if not all) inherit directly from Exception instead of from StandardError. The documentation also seems to suggest this use for users exception. Now I was wondering if it wouldn't be better that for exception that indicate some error condition that these would inherit from StandardError and that this would be indicated in the documentation and reflected in the stdlib? Would it break much code to make this change? My first impression would be no, but I could be missing something. -- Antoon Pardon From fredrik at pythonware.com Wed Mar 22 02:17:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Mar 2006 08:17:19 +0100 Subject: doctest, unittest, or if __name__='__main__' References: <1142974528.143287.326360@e56g2000cwe.googlegroups.com> <20060321173942.57d12ce7@samwise.anansi> Message-ID: Terry Hancock wrote: > Doctest is very easy to use, so it's easy to ensure that > tests get written. OTOH, they're only really good for stuff > that can be easily tested in the interpreter (e.g. that can > be easily verified from their text output). When you get > into stickier stuff like graphics and web programming, the > formal structure of pyunit can be easier to adapt than > something which is intrinsically based on string processing. that's puzzling. I do lots of graphics, and some web programming (my company's main product is a web application server for graphics), and we use doctest for everything. I find it a bit odd that someone thinks that there are tests for which assert something == somevalue is easier to write than either >>> something somevalue or >>> something == somevalue True From lists at fabis-site.net Sun Mar 19 12:34:15 2006 From: lists at fabis-site.net (Fabian Steiner) Date: Sun, 19 Mar 2006 18:34:15 +0100 Subject: C-API: A beginner's problem In-Reply-To: References: Message-ID: Heikki Salo wrote: > Heikki Salo wrote: >> Fabian Steiner wrote: >>> What did I do wrong? As I am quite new to C, I probably made many >>> mistakes, so please feel free to correct me. >> >> The following line: >> >> > for (i = 0; i <= seqlen; i++) { >> >> Should be "for (i = 0; i < seqlen; i++) {". Otherwise the last >> assignment will be out of bounds and probably corrupts heap. > > And closer look tells that the code should not even compile. Is the code > cut & pasted directly? Line "list[i] = item;" tries to assign a pointer > to an int-array, which should not compile. There are other similar > oddities. Okay, thank you (and the others) for these hints. As you see, I am quite new to C and I just wrote these lines by using parts I have found in the newsgroup. Unfortunately, the Python C-API documentation / tutorial won't help me since it is quite difficult to understand because of the lack of basics. What do I have to change in order to make the code work? Thank you very much in advance! Cheers, Fabian From godoy at ieee.org Fri Mar 3 20:20:39 2006 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 03 Mar 2006 22:20:39 -0300 Subject: how do you move to a new line in your text editor? References: <%ZGNf.1711$No6.40016@news.tufts.edu> <1141325510.264691.215260@t39g2000cwt.googlegroups.com> <1vkeaw8hiszrg.dlg@rikodespammed.com> <1x894qbcsr62h.dlg@rikodespammed.com> Message-ID: <87u0af80pk.fsf@ieee.org> Mc Osten writes: > Because I tried it and it just lacks a lot of functionality you get with > TextMate or Emacs. It is quite stupid when indenting, just to name one. This is the main motive I don't use PyDev with Eclipse... It is a lot more stupid than python-mode on Emacs with regards to indenting... :-( -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From josecarlos.balderas at gmail.com Fri Mar 31 14:43:40 2006 From: josecarlos.balderas at gmail.com (Jose Carlos Balderas Alberico) Date: Fri, 31 Mar 2006 21:43:40 +0200 Subject: Working with files in a SimpleXMLRPCServer Message-ID: Oops, I'm afraid I replied to Brian only instead of to the whole distribution list. I copy the message I sent to him so that everyone can read it: I'm afraid I cannot use the zlib library provided by Python, since the ZIP files I'm supposed to send must be password-protected, and I haven't been able to find a method in the library that let me zip a file with a password. I could be wrong though... As for the HTTP server instead of the XML-RPC one... you are totally right. However, in the specification I was handled to perform my task, it said explicitely to use the XML-RPC protocol; maybe it has to do because there is also some data-bases issues in our application, and using XML-RPC would be more appropiate. For example, the text file I'm supposed to zip has its information extracted from a database table. Anyway, since those are the constraints I'm facing, I thought handling the files issue the way I did would be more appropiate. Since I have never done network programming till now, I'm having difficulties dealing with it, and I want to know if the solution I chose is acceptable. Thank you very much. Cheers, -------------- next part -------------- An HTML attachment was scrubbed... URL: From codecraig at gmail.com Wed Mar 8 08:28:13 2006 From: codecraig at gmail.com (abcd) Date: 8 Mar 2006 05:28:13 -0800 Subject: PyCon2006 - will the content be available for download? Message-ID: <1141824493.358952.106780@i40g2000cwc.googlegroups.com> Anyone know if (and when) the talks from PyCon2006 will be available for download. I am particularly interested in the tutorials (as they did not have them at PyCono2005). Thanks. From samschul at pacbell.net Sat Mar 4 20:27:06 2006 From: samschul at pacbell.net (sam) Date: 4 Mar 2006 17:27:06 -0800 Subject: The old round off problem? In-Reply-To: References: <1141498826.719803.114490@u72g2000cwu.googlegroups.com> <7xslpxki8p.fsf@ruckus.brouhaha.com> Message-ID: <1141522026.813636.33310@i40g2000cwc.googlegroups.com> David I beg I beg Can you answer the question? Also thanks for the information on using the Taylor series. Sam Schulenburg From nick at craig-wood.com Tue Mar 14 13:30:04 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 14 Mar 2006 12:30:04 -0600 Subject: Tried Ruby (or, "what Python *really* needs" or "perldoc!") References: <1142355126.757569.42160@i40g2000cwc.googlegroups.com> Message-ID: john_sips_tea at yahoo.com wrote: > IMO, Perl has docs nailed. I learned Perl before coming > to Python, and I can tell you that their docs kick butt. > I believe the reason why is (besides Larry's excellent > and entertaining writing) because of perldoc. Here's how > it works: they write special doc directives into their .pl > files that the interpreter ignores, but that the perldoc > command processes into a manpage for you. This is a *bit* > like what pydoc does, only pydoc just regurgitates docstrings, > while perldoc formats special directives into headings, code > listings, bulleted lists, etc. As another perl refugee I agree with you 100% here. "perldoc perltoc" then "perldoc xxxx" will find you anything in perl. Its frustrating that pydoc is only half (or less) of the docs. However having bedded into python for a few years, I now just reach for my web browser for the global module index instead of pydoc. Its not as good as perldoc as it doesn't cover all the modules I've got installed, but its very good documentation. Some modules have good pydoc-umentation but not all of them. Code examples tend to be missing. I think a major problem with our way of thinking about perldoc/pydoc/man pages is that it is a) unix centric, and b) possibly a bit old fashioned! a) and b) apply to perl certainly, but I don't think they apply to python in the same way. I'd love to have a unified documentation system where *all* the documentation for *all* installed modules was available to pydoc *and* the web browser and *all* this documentation was in .py files. (Putting the code together with the documentation is essential in my opinion and experience - if you seperate the two then the documention will lag the code.) PS I've used reST and perldoc. reST is easier to use for the easy things, but gets complicated for the hard things. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From pl.leroy at free.fr Fri Mar 3 16:03:31 2006 From: pl.leroy at free.fr (pierlau) Date: Fri, 03 Mar 2006 22:03:31 +0100 Subject: Writing an OPC client with Python ? In-Reply-To: <4408A1C8.6080004@websafe.com> References: <440880b4$0$13692$636a55ce@news.free.fr> <4408A1C8.6080004@websafe.com> Message-ID: <4408aeca$0$12868$626a54ce@news.free.fr> Larry Bates a ?crit : > > pierlau wrote: > >>Hello, >> >>I use an OPC server for connection to DC Drive. >>I would like to write a small OPC client. >>I have the dll OPCDAAuto.dll which contains all class and method but I >>wonder if its possible to instance in python the class that are in the dll ? >> >>Thanks for your help . >> >>Pierre >> >> >> > > > You can call methods/functions in a .dll using ctypes. > > http://starship.python.net/crew/theller/ctypes/ > > -Larry Bates I have tried with ctypes. I acheived to load the library it works when I use following instructions : print windll.OPCDAAuto or print cdll.OPCDAAuto (i see an handle number) But I can't run the functions? I there a way to 'see' the inside of the dll (i.e. to list the methods) ? From fredrik at pythonware.com Sun Mar 12 04:17:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Mar 2006 10:17:17 +0100 Subject: Cheese Shop: some history for the new-comers References: <44126523$0$1016$afc38c87@news.optusnet.com.au> Message-ID: A.M. Kuchling wrote: > richard wrote: > > So I did what people always do in this situation, I asked Barry Warsaw to > > name. it. And he did, "Cheese Shop". I liked the name, so it was done. When > > the new pydotorg machines went live last year, so too did the name > > cheeseshop.python.org > > Given the endless whiny complaints about the name, though, I think we > should just give up and go back to PyPI (pronounced 'Pippy'). just change the link on the main site to read "packages", change the self- references on the cheeseshop.python.org page to "Packages" or "Package Index", move the quote down to the bottom of the page, and and leave the rest as is. From SpamBlocked at tbdata.com Wed Mar 29 06:41:11 2006 From: SpamBlocked at tbdata.com (William Tasso) Date: Wed, 29 Mar 2006 12:41:11 +0100 Subject: Content Management System References: <1143627824.174540.13710@z34g2000cwc.googlegroups.com> <442a6bea$0$36938$4fafbaef@reader3.news.tin.it> Message-ID: [Follow-ups suggested] Fleeing from the madness of the J2be - IT Services jungle J2be stumbled into news:comp.lang.python,comp.lang.php,alt.www.webmaster,comp.infosystems.www.authoring.misc,microsoft.public.sharepoint.portalserver and said: [attribution lost] >> You will just be dumping files >> on another remote server. How will the users "find" what they want? > It's not a *dumping* files but publishing contents. One could be forgiven for misidentifying one for the other based on that which is to be found on the WWW. -- William Tasso whither a trophy? From luca.tavoletti at gmail.com Thu Mar 16 04:52:23 2006 From: luca.tavoletti at gmail.com (lux) Date: 16 Mar 2006 01:52:23 -0800 Subject: Button and Key Event In-Reply-To: <1142459295.780632.291390@e56g2000cwe.googlegroups.com> References: <1142422794.772939.161390@z34g2000cwc.googlegroups.com> <1142459295.780632.291390@e56g2000cwe.googlegroups.com> Message-ID: <1142502743.790439.260300@u72g2000cwu.googlegroups.com> Thanks, I think that the solution for my problem is only to use an AcceleratorTable. In this way I can capture the key pressed event without the "button problem" Luca From fakeaddress at nowhere.org Sun Mar 5 11:57:46 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 05 Mar 2006 16:57:46 GMT Subject: Random Prime Generator/Modular Arithmetic In-Reply-To: <1141512951.983754.74980@i40g2000cwc.googlegroups.com> References: <1141487100.450422.306010@v46g2000cwv.googlegroups.com> <7x1wxhlx07.fsf@ruckus.brouhaha.com> <1141512951.983754.74980@i40g2000cwc.googlegroups.com> Message-ID: Tuvas wrote: > Okay, I don't know if your farmiliar with the miller-rabin primality > test, Paul is familiar with it. When he referred to your Miller-Rabin test, he meant all the rounds. > but it's what's called a probabalistic test. Meaning that trying > it out once can give fake results. In the sense that some composites will pass as prime for some bases. > For instance, if you use the number > 31 to test if 561 is prime, you will see the results say that it isn't. That's not an instance of a fake result; Miller-Rabin has that one right. When Miller-Rabin says a number is composite, it is always correct. Your current Miller-Rabin test, in http://www.geocities.com/brp13/Python/modular.html in method Mod.is_strong_pseudo_prime(), looks buggy. Obviously you want "cut()" not "cut", and "if 1:" cannot fail. In my opinion, the Mod class is not such a good idea; just use functions. Note that Python has modular exponentiation built in. pow(base, power, modulus) with positive integer arguments will return base**power % modulus. Finally, though most introductory crypto courses don't cover it, RSA requires "padding" of the plaintext data. Google RSA + Padding for more. Or ask on sci.crypt. -- --Bryan From aleaxit at yahoo.com Sat Mar 11 16:48:57 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 11 Mar 2006 13:48:57 -0800 Subject: Why property works only for objects? References: <1hbyfgj.a3p39r1smomavN%aleaxit@yahoo.com> <4412107a$0$22499$636a55ce@news.free.fr> <1hbzzh7.1qlkv8hokpiqzN%aleaxit@yahoo.com> <1hc1abj.1fokrj9826uvjN%aleaxit@yahoo.com> Message-ID: <1hc1fgy.5nq08nvj7qkaN%aleaxit@yahoo.com> Michal Kwiatkowski wrote: ... > Alex Martelli napisa?(a): > >>>> obj.__dict__ > > {} > > > > ...the presence of '__dict__' as an entry in C is confusing the issue, > > because that's what you get in this case as obj.__dict__. > > It still bugs me. What's the actual procedure when doing attribute > assignment? I understand it like this: > > obj.attr = value > * if instance class has __setattr__, call it > * else: if class has an attribute with name "attr" check if it's a > descriptor; when it's overriding descriptor, call its __set__ > method, otherwise raise AttributeError > * else: bind "attr" as object attribute Yes, this is correct. > I've initialized C.__dict__ as plain dictionary, so it's not a > descriptor. C also doesn't have __setattr__ method. I'm probably wrong, > as __dict__ is considered somewhat special, but I can't really > understand to which degree. Any other attribute I try to bind to object > will be stored inside object dictionary, without looking up class > dictionary. __dict__ is special, because it's *the* dictionary that > stores all references to object's attributes. So, when assigning to > __dict__ I would expect old dictionary to be simply replaced with this > one. I don't understand why class attributes has any factor in this. As I said, it looks to me like you've found a bug here. __dict__ (like all names starting and ending in double underscores) is special, in the sense that Python can do with it whatever it wishes, but there is neither any documentation nor any reason explaining the behavior you have observed. > > C.__dict__ gives you a dictproxy, not a real dict, by the way: > > > >>>> obj.__dict__ is C.__dict__['__dict__'] > > True > > Why is that? I've initialized it as dictionary. When the type was > changed and why? Is this used anywhere? That's type(C)'s doing, and as such, perfectly correct: C.__dict__ for any type C always returns a dictproxy (so that Python, internally, doesn't _have_ to use a real dict, but rather a structure of slots that may be much more compact and fast to access). > > The funny thing is that builtins like var, which should know better, > > also get fooled...: > > > >>>> vars(obj) > > {} > >>>> vars(obj) is C.__dict__['__dict__'] > > True > > Docstring for vars says: > With an argument, equivalent to object.__dict__. > > So this behavior simply conforms to the doc. But the behavior of obj.__dict__={} doesn't. > > I think a fair case can be made that you've found a bug in Python here: > > the existence of that __dict__ in C's class body is clearly causing > > unintended anomalies. Fortunately, getattr and friends don't in fact > > get confused, but vars does, as does assignment to obj.__dict__... > > What solution do you propose? Opening a bug report on the Python bugtracker would maximize the likelihood that something gets done about this bug. Alex From aisaac0 at verizon.net Mon Mar 27 09:45:31 2006 From: aisaac0 at verizon.net (David Isaac) Date: Mon, 27 Mar 2006 14:45:31 GMT Subject: access mbx files? References: <1143441652.512507@yasure.drizzle.com> Message-ID: Donn Cave, donn at drizzle.com > I suppose it isn't supported by the mailbox module basically because > it isn't all that commonly encountered. It may be more common on mail > servers, but there it's email net protocol data, POP or IMAP. If > Mahogany has been using this format for `local' folders (i.e., via > filesystem), I think that may have been kind of poor judgement on the > part of its developers. I cannot judge that, although I think I recall the choice was made for reasons of speed. What do you see as the downsides? Just that it is uncommon (and thus questions like my original questions arise)? Thanks, Alan Isaac From http Thu Mar 30 14:28:54 2006 From: http (Paul Rubin) Date: 30 Mar 2006 11:28:54 -0800 Subject: any() and all() on empty list? References: <442B9AF7.2010407@REMOVEMEcyber.com.au> <7xu09gicko.fsf@ruckus.brouhaha.com> <442BAAA5.8010009@REMOVEMEcyber.com.au> Message-ID: <7xwtebpw95.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > No, all(seq) is true if you can't point to a specific element in seq > > that's false. > > No, all(seq) is true if every element in seq is true. Surely that's a > more intuitive definition than your definition by what you can't do. They are different? I'd say every element in seq is true, unless there's an element that's false. Do you want to pick a different word than "all" and suggest renaming the function? > Here's another way of looking at the problem: > > all(flying elephants which are pink) => true > all(flying elephants which are not pink) => true > > So, these flying elephants -- are they pink or not? By the definition, "all flying elephants are pink" and "all flying elephants are non-pink" are both true statements, if that's what you're asking. There is no contradiction. It's one of those questions like "have you stopped beating your wife". I'd say: def boolify(s): return map(bool, s) then: all(S) = reduce(operator.and_, boolify(S), True) any(S) = reduce(operator.or_, boolify(S), False) You can see that changing True to False in the above definition of all would make the result always false. FWIW, I threw all my TV sets off the roof of my building this morning. But nobody on the sidewalk needed to worry about getting hit by one ;-). From sybrenUSE at YOURthirdtower.com.imagination Thu Mar 2 10:30:08 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 2 Mar 2006 16:30:08 +0100 Subject: white space in expressions and argument lists References: Message-ID: John Salerno enlightened us with: > To me, the space makes it nicer and more readable, but I was > surprised to read in Guido's blog that he thinks 1+2 should be the > normal way to write it. What does everyone else think? I usually write 1 + 2 and func(a, b). Sometimes I even use more spaces to align stuff: foo = 'bar' foobar = 42 azimov = 3 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 weekender_ny at yahoo.com Wed Mar 8 00:06:35 2006 From: weekender_ny at yahoo.com (John) Date: 7 Mar 2006 21:06:35 -0800 Subject: sending a text message via webpage button Message-ID: <1141794395.277013.245680@e56g2000cwe.googlegroups.com> Can anyone help me in coding a script that can send a text message typed to the script like. sendmessage 6318019564 "test message" What I want to do is fill up this information on this webpage http://www.cingularme.com/do/public/send;jsessionid=aKDwXM1S0Reh and click the submit button using the python script. Any ideas on how to do this or if someone has already done this? Thanks, --j From roy at panix.com Wed Mar 8 19:28:54 2006 From: roy at panix.com (Roy Smith) Date: Wed, 08 Mar 2006 19:28:54 -0500 Subject: is there any overheard with try/except statements? References: Message-ID: In article , John Salerno wrote: > One of the things I learned with C# is that it's always better to handle > any errors that might occur within the codes itself (i.e. using if > statements, etc. to catch potential out of range indexing) rather than > use too many try/catch statements, because there is some overhead every > time the program encounters the try. > > Is this the case at all with Python, in terms of extra work or slower > speed? Or is try/except implemented differently in Python than it is in > other languages, so that it runs just like any other code? > > Thanks. Repeat after me: "Python is not " In C++ (and, I assume, C#), exception handling is relatively expensive, and is avoided for this reason. It's also avoided (in C++, anyway) because it's only in the past few (5-10) years that you could pretty much count on whatever compiler you were using implementing them correctly. Lastly, many C++/C# programmers came from C, where exceptions don't exist, so they're not used to using them. But, that's not Python. In Python, exceptions work as advertised, and they're cheap. The pythonic way to do things is to embrace the maxim that "it's easier to ask forgivness than to ask permission". It is usually cleaner and faster to write a try block than an if statement. For example, I'll write: try: x = foo[y] except IndexError: blah instead of if y < len (foo): x = foo[y] else: blah every time. From invest at vosar.net Thu Mar 9 22:02:26 2006 From: invest at vosar.net (ISRAEL FAGBEMI) Date: Thu, 9 Mar 2006 22:02:26 -0500 Subject: BECOME A DOT.COM MILLIONAIRE WITH ONLY $5.99Cents or $1K. Message-ID: <6%5Qf.90916$8d1.24333@read1.cgocable.net> An HTML attachment was scrubbed... URL: From webraviteja at gmail.com Fri Mar 31 15:40:35 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 31 Mar 2006 12:40:35 -0800 Subject: Looking for a language/framework In-Reply-To: <1hcwg6n.b3jwv5xq910tN%aleaxit@yahoo.com> References: <1143559444.045808.38790@u72g2000cwu.googlegroups.com> <1hcwg6n.b3jwv5xq910tN%aleaxit@yahoo.com> Message-ID: <1143837635.846033.204910@u72g2000cwu.googlegroups.com> > For example, I've never seen an "object-relational mapping" (technical > term for cruft that tries to avoid people having to learn and use SQL) > which doesn't drive me into a murderous, foam-at-mouth rage in a very > short time -- I *WANT* my SQL, I *LOVE* SQL, it's *WAY* more powerful > and suitable for access to data than all those simulated "OO DB" people > lay on top of it (of course, that does depend on having a REAL > relational DB underneath, not, say, MySQL;-). Other people disagree > very, very deeply with my preferences (as proven by the existence of a > begazillion ORMs, including general-purpose ones as well as ones that > are part of web-application frameworks). I for one don't have any particular love for SQL. For most purposes I don't want to be bothered with its details. However, I am disillusioned with ORMs. With SQL and old school database management, I had tools such as QBEs, ERD managers to visually manage much of the details (I perform better with pictures than text) and even if others disagree, it worked well for me. Now with ORMs, I am back to code again. Granted, it appears cleaner most of the time but I want to be able to not see it at all. Java ORMs are begining to get a lot of these tools now. But I have been cautious to dip my toes in these cold (verbose, XML infested) waters so far. From aleaxit at yahoo.com Sun Mar 12 11:38:29 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 12 Mar 2006 08:38:29 -0800 Subject: Why property works only for objects? References: <1hbyfgj.a3p39r1smomavN%aleaxit@yahoo.com> <4412107a$0$22499$636a55ce@news.free.fr> <1hbzzh7.1qlkv8hokpiqzN%aleaxit@yahoo.com> <1hc1abj.1fokrj9826uvjN%aleaxit@yahoo.com> <1hc1fgy.5nq08nvj7qkaN%aleaxit@yahoo.com> <1hc1q2d.44bzrca7iz86N%aleaxit@yahoo.com> Message-ID: <1hc2vld.ete6omjy97iN%aleaxit@yahoo.com> Michal Kwiatkowski wrote: ... > > No, the value found in the instance (your second 'else' here) takes > > precedence if the descriptor found in the first 'else' is > > non-overriding. > > Oh, right. My mistake comes from the subtle difference between defining > descriptor as a class and by property() builtin (I've tested only second > option and assumed that descriptor without __set__ cannot be rebinded): property is always overriding, of course, since type property does have a property.__set__ (which raises an exception if you build the instance of property w/o a setter function). > class non_overriding(object): > def __get__(*a): > return 12 > > class C(object): > x = non_overriding() > y = property(lambda s:23) > > c = C() > > c.x = 4 > print c.x # => 4 > > c.y = 5 # => AttributeError: can't set attribute Right: another example of overriding and nonoverriding descriptors. > IMHO that's not very consistent. How so? Given the lower-level semantics of descriptors (and the distinction between overriding and non), are you suggesting that property should not be a type but a factory function able to return instances of either overriding or non-overriding types? I'm not sure how that complication would make things "consistent" in your view. > Well, probably some code rely on this, > so I just have to live with it. Backwards-incompatible changes can be proposed for Python 3.0, if they lead to a situation that's preferable to what we have now. I just don't see what you mean about "not very consistent" and what you would prefer the language and built-ins to be. Alex From aleaxit at yahoo.com Sun Mar 5 14:15:35 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Mar 2006 11:15:35 -0800 Subject: beginner question on dinamin buiding of arg list References: Message-ID: <1hbq4kn.7rwriw1hhtdonN%aleaxit@yahoo.com> Sandro Dentella wrote: > I need to build-up an arg list to pass to a function. > > Suppose I have a dictionary: > > opts = { 'user' : 'jack', 'addr' : 'Green Str.'} > > and I want to build a cmd line like this: > > select( user='jack', addr='Green Str.' ) select(**opts) should fit the bill. (it.comp.lang.python is the Italian newsgroup about Python, by the way;-). Alex From irmen.NOSPAM at xs4all.nl Fri Mar 3 09:43:11 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 03 Mar 2006 15:43:11 +0100 Subject: do design patterns still apply with Python? In-Reply-To: References: <8SINf.1718$No6.40137@news.tufts.edu> <1141394593.588174.321660@z34g2000cwc.googlegroups.com> Message-ID: <44085602$0$11067$e4fe514c@news.xs4all.nl> Roy Smith wrote: > >> For example, the Factory pattern is mostly to work around the fact that >> it's difficult in Java and C++ to dynamically load classes. > > You're over-specifying. Most of most design patterns is to work around the > fact that it's difficult in Java and C++ to do many things. +1 QOTW! --Irmen From alainpoint at yahoo.fr Tue Mar 14 07:43:40 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 14 Mar 2006 04:43:40 -0800 Subject: Is this possible in Python? SOLUTION FOUND In-Reply-To: <1142331474.355167.20970@i40g2000cwc.googlegroups.com> References: <1142238871.199749.243470@p10g2000cwp.googlegroups.com> <1142282467.270698.142780@p10g2000cwp.googlegroups.com> <1142331474.355167.20970@i40g2000cwc.googlegroups.com> Message-ID: <1142340220.720530.27590@p10g2000cwp.googlegroups.com> jalanb wrote: > You might like the version here: > http://www.jorendorff.com/toys/out.html > > Especially the "need to know" presentation, which is cute > > -- > Alan > http://aivipi.blogspot.com Thank you for the tip. Meanwhile, I found a shorter solution to my problem: def magic(arg): import inspect return inspect.stack()[1][4][0].split("magic")[-1][1:-1] assert magic(3+4)=="3+4" Alain From elpX at adsihqX.com Thu Mar 9 21:24:14 2006 From: elpX at adsihqX.com (Dr. Pastor) Date: Fri, 10 Mar 2006 02:24:14 GMT Subject: About IDLE? In-Reply-To: <1141950875.398548.75180@p10g2000cwp.googlegroups.com> References: <2i3Qf.3304$Bj7.629@newsread2.news.pas.earthlink.net> <1141950875.398548.75180@p10g2000cwp.googlegroups.com> Message-ID: Thank you! I can see only your reply. But indeed google prints three. The mind boggles. Nick Smallbone wrote: > Dr. Pastor wrote: > >>Any reply? >> > > > ahem. three replies, when i counted: > http://groups.google.com/group/comp.lang.python/browse_frm/thread/ab0c8455251e616c/ > From nospamformeSVP at gmail.com Tue Mar 14 21:55:12 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Tue, 14 Mar 2006 21:55:12 -0500 Subject: Printable string for 'self' In-Reply-To: References: Message-ID: Michael Spencer wrote: > > > In general, this requires exhaustive search of name bindings e.g.,: > > >>> def get_names_of(obj, ns): > ... return [name for name, value in ns.iteritems() if value is obj] > ... > >>> class A(object): > ... def global_names_bound_to_me(self): > ... return get_names_of(self, globals()) > ... > >>> a = A() > >>> a.global_names_bound_to_me() > ['a'] > >>> b = a > >>> a.global_names_bound_to_me() > ['a', 'b'] > >>> > Ah, ok. But, as you show in the example, this technique does not let me figure out which of 'a' or 'b' was used to qualify global_names_bound_to_me(). And if I call my method: A().qualify global_names_bound_to_me() then I get an empty list back. Is what I want to do not possible without referring back to the source? Don. From root at randpoly.com Mon Mar 20 01:32:11 2006 From: root at randpoly.com (randpoly.com PostMaster) Date: Mon, 20 Mar 2006 12:02:11 +0530 Subject: Error sending message [1142579362378.1884.rpppl] from [randpoly.com] Message-ID: <20060320092726.7BA8A2DF48E@smtp41.smtp4u.com> [<00>] V-POP3bounce: Rcpt=[madmax at appelsiini.net];Error=[550 Error: Invalid Attachment] [<01>] Error sending message [1142579362378.1884.rpppl] from [randpoly.com]. ID: Mail From: Rcpt To: Server: [209.120.245.170] [<02>] The reason of the delivery failure was: 550 Error: Invalid Attachment [<05>] Here is listed the initial part of the message: Received: from python.org (192.168.0.24:4368) by smtp.randpoly.com with [V-POP3Mail (Win32/Ix86) ESMTP Server] id for from ; Fri, 17 Mar 2006 12:39:22 +0530 From: python-list at python.org To: madmax at appelsiini.net Subject: hello Date: Fri, 17 Mar 2006 12:51:11 +0530 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_0007_20D01A2C.9CCD2AD1" X-Priority: 3 X-MSMail-Priority: Normal From rrr at ronadam.com Sun Mar 26 17:48:40 2006 From: rrr at ronadam.com (Ron Adam) Date: Sun, 26 Mar 2006 16:48:40 -0600 Subject: Accessing func_name from inside a function In-Reply-To: <1hct5wu.nl1a63sbhn19N%aleaxit@yahoo.com> References: <1143309619.566327.173640@j33g2000cwa.googlegroups.com> <1hcs34g.1f6lnx81ic59i5N%aleaxit@yahoo.com> <1hct5wu.nl1a63sbhn19N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Ron Adam wrote: > >> A "Current" key word would fix this. Or possibly "This" which would be >> short for "This object". > > I think "This" would cause huge confusion, since in other popular > language the keyword "this" means (a pointer/reference to) "the instance > variable on which the method is being called" -- my use is instead for > "the object of the immediate lexically enclosing scope" (a module, > class, or function). Implementation wouldn't be trivial in today's > CPython, anyway: frames have no references at all to function objects > (only to _code_ objects), and class objects don't even exist untill well > after their top-level code has long finished running; to make Current > possible, these subtle points of semantics would have to be changed in > quite a revolutionary way, especially where classes are concerned. > > > Alex Yes, I figured it would not be an easy or simple addition. An easier alternative might be to be able to limit specific name rebindings. Then some names could be depended on to always point to a specific object. Something like that would need to be used sparingly I think. Cheers, Ron From max at alcyone.com Sun Mar 19 18:07:10 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 19 Mar 2006 15:07:10 -0800 Subject: Unpythonic? Impossible?? In-Reply-To: <485ep5Fij70mU1@individual.net> References: <485ep5Fij70mU1@individual.net> Message-ID: BrJohan wrote: > I know how to use a class factory - and could work around using such a > mechanism. However I am interested to know if I could let the classes do the > work by themselves. You can, but a class factory is going to be much clearer and probably more maintainable. From the user's perspective, there's no difference from calling a class A to instantiate it, and calling a factory function called A that selects the appropriate class and returns an instance of it. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Never had very much to say / Laugh last, laugh longest -- Des'ree From reply.in.the.newsgroup at my.address.is.invalid Sun Mar 19 19:25:55 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 20 Mar 2006 01:25:55 +0100 Subject: Is there such an idiom? References: <1142813592.486643.111550@j33g2000cwa.googlegroups.com> Message-ID: Per: >how to find whether there is/are common item(s) between two list >in linear-time? To find items in common between two lists, make the first into a dictionary and then look for items in the second in it. -- Ren? Pijlman Wat wil jij leren? http://www.leren.nl From Aiwass333 at gmail.com Fri Mar 31 12:48:02 2006 From: Aiwass333 at gmail.com (RunLevelZero) Date: 31 Mar 2006 09:48:02 -0800 Subject: re.sub problem In-Reply-To: <1143825251.401962.247900@u72g2000cwu.googlegroups.com> References: <1143812012.143560.24370@i40g2000cwc.googlegroups.com> <1143822424.549401.250090@z34g2000cwc.googlegroups.com> <1143825251.401962.247900@u72g2000cwu.googlegroups.com> Message-ID: <1143827282.384038.161180@i39g2000cwa.googlegroups.com> Glad I could help. From reply.in.the.newsgroup at my.address.is.invalid Sat Mar 11 19:03:36 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sun, 12 Mar 2006 01:03:36 +0100 Subject: Python IDE: great headache.... References: <1142120002.912902.69630@i40g2000cwc.googlegroups.com> Message-ID: Sullivan WxPyQtKinter: >I hope that an IDE should be featured with: I use WingIDE 2.1.0 (beta1) and I'm pleased with it. >1. Grammar Colored highlights. Yes, Wing does that. >2. Manage project in a tree view or something alike, ie, a project file >navigator. Yes. >3. Code collapse and folding. Yes. >4. Code auto-completion: especially prompting function parameters when >I am typing a function previously defined by myself. Like the one in >Visual Studio series. Yes (well, hints in a separate pane, no prompting). >5. Debugging: Breakpoints, conditional pause. watch for variables.step >into, over and out of a function. Yes. >6.Indentation management like in IDLE: press ctrl+[/] to modify the >identation of a line or a block. Yes. -- Ren? Pijlman From 3dbernard at gmail.com Mon Mar 27 17:14:23 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 27 Mar 2006 17:14:23 -0500 Subject: Problems writing to file In-Reply-To: <61d0e2b40603211349p23aaba77yc2648012fa9f0f77@mail.gmail.com> References: <61d0e2b40603211247pf3bdb9cqf64469d4d77a7a5c@mail.gmail.com> <442069B3.6040500@islandtraining.com> <61d0e2b40603211349p23aaba77yc2648012fa9f0f77@mail.gmail.com> Message-ID: <61d0e2b40603271414i5ea273adjd7f5e00f99756777@mail.gmail.com> Hello everyone! I seem to have found the problem! In my program, I have "print" commands. These print commands are turned off only when the "noprint" command line argument is supplied. When the Linux service launched the program, it was not using the "noprint" argument. When I started using it, everything went back to normal! Anyone has a take on this behavior? Thanks Bernard On 3/21/06, Bernard Lebel <3dbernard at gmail.com> wrote: > Hi Gary, > > That is actually what I do. Each time the program prints something to > the file, it flushes the buffer. I also tried opening and closing the > file, same result. > > I could indeed post the code. That is only a fraction of the program, > as the log is managed through the Queue module: > > > > > def __nodeLog( self, iCallerLevel, sJobID, sMsg ): > > """ > The method checks for an override in loglevel given by command line argument. > If such override has been set (using the 'loglevel' argument), then > the command line value is used. > > ARGUMENTS: > iCallerLevel (integer): level of verbosity to use, applies only to > node type of logging > sJobID (string): the JobID of the job, if applies > sMsg (string): node line to print > """ > > # Check if a log level was set through command line > if 'loglevel' in dCmdLineArgs: > # Log level set through command line, override any other log level > sLogLevel = dCmdLineArgs[ 'loglevel' ] > iLogLevel = int( sLogLevel ) > else: > iLogLevel = self.loglevel > > > > if iCallerLevel <= iLogLevel: > > # Forge line to print into node log > sLine = '%s %s [jobid: %s]: %s\n' % ( NAME, time.ctime(), str( > sJobID ), sMsg ) > if self.printmsg == True: print sLine > > > # Check if user specified extraction command line arguments > for sArg, tValue in dCmdLineArgs.items(): > if 'extractlog' in sArg: > sLogLevel = tValue[0] > sLogType = tValue[1] > > # Check if caller level is same as log level defined by the > extract argument > if str( iCallerLevel ) == sLogLevel: > sExtractLogFile = os.path.join( self.NODELOGS, '%s_%s.log' % ( > NAME, sLogType ) ) > self.__output( sExtractLogFile, sLine ) > > > self.__output( self.MAINLOGFILENAME, sLine ) > > > > > > def __output( self, sLogFile, sLine ): > > """ > Try to write to the log file. > > ARGUMENTS: > sLogFile (string): the log file > sPrint (string): the line to print > """ > > # Try 3 times to write to the output file > > for i in range(3): > > # Try to output the message > > try: > oLogFile = file( sLogFile, 'a+' ) > oLogFile.write( sLine ) > oLogFile.close() > > return LOGOPSUCCESS > > except IOError: > if i == 2: > if self.printmsg == True: > print '\nERROR > log.__output : All attempts to write to log > file %s failed, latest updates will be lost.\n' % ( sLogFile ) > return LOGOPFAILURE > else: > if self.printmsg == True: > print '\nWARNING > log.__output : Attempt "%i" to write to log > file %s raised IO Error, next attempt in %s seconds.\n' % ( i+1, > sLogFile, self.LOGWAITTIME ) > > > > > Thanks > Bernard > > > > On 3/21/06, Gary Herron wrote: > > Bernard Lebel wrote: > > > > >Hello, > > > > > >I have this strange problem. I have written a program that writes a > > >log to a log file. > > > > > >To start the program (I'm on Linux Fedora Core 3), I used a service. > > >This service runs a bash file, wich in turn runs the Python top > > >program file. > > > > > >Sooner or later the program stops writing to the log file. I have > > >absolutely no clue why would that happen. Since the output of the > > >Python program is not redirected other than to this log file, I have > > >no idea why it's doing this. But the Python process appears still > > >alive and well! > > > > > >But the strange thing is that if I run the program directly from a > > >bash shell, no problem whatsoever, the programs runs smoothly and > > >never stops writing to the file, until I kill it. > > > > > > > > >Any suggestion? > > > > > > > > > > > >Thanks in advance > > >Bernard > > > > > > > > Perhaps ... > > > > Output is normally buffered in memory until some threshhold is reached, > > at which point the whole buffer is written, and the process repeats. If > > your output quantity is small, and your impatience is high, you may be > > declaring failure before the buffer fills and triggers a write. The > > solution would be to call flush on the output file after each write (or > > perhaps just wait more patiently). > > > > If the output is voluminous, then it's probably something else ... but I > > don't know what. Perhpas you could post your code. > > > > Gary Herron > > > > > From fredrik at pythonware.com Sat Mar 11 11:52:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 11 Mar 2006 17:52:15 +0100 Subject: Old Python Logo References: <1142095200.056208.83360@j52g2000cwj.googlegroups.com> Message-ID: "Spinchange" wrote: > Can someone post a link or email me an image of the old Python logo? > I'd like to save a copy of it, I rather liked it - very retro. the dot matrix logo ? you can get a copy from this page: http://pydotorg.dyndns.org:8000/PythonOrg.html From http Sun Mar 19 18:23:37 2006 From: http (Paul Rubin) Date: 19 Mar 2006 15:23:37 -0800 Subject: Unpythonic? Impossible?? References: <485ep5Fij70mU1@individual.net> Message-ID: <7xu09u9fye.fsf@ruckus.brouhaha.com> Erik Max Francis writes: > You can, but a class factory is going to be much clearer and probably > more maintainable. From the user's perspective, there's no difference > from calling a class A to instantiate it, and calling a factory > function called A that selects the appropriate class and returns an > instance of it. I remember having a similar problem involving multiple base classes and deciding that factory functions couldn't do quite what I wanted. Here's a thread about it, with a recipe using metaclasses by Roeland Rengelink: http://tinyurl.com/rz6ne Unfortunately, the subtleties of what I was trying to do now escape me. From epost2 at gmail.com Fri Mar 10 13:07:22 2006 From: epost2 at gmail.com (Bruce) Date: 10 Mar 2006 10:07:22 -0800 Subject: Use python to process XML file In-Reply-To: <1142010641.770379.229230@j52g2000cwj.googlegroups.com> References: <1142010641.770379.229230@j52g2000cwj.googlegroups.com> Message-ID: <1142014042.518683.73770@j33g2000cwa.googlegroups.com> you can use function parse from xml.sax It takes your xml as the first argument and an xml.sax.handler.ContentHandler instance as the second. --- from xml.sax import parse from xml.sax.handler import ContentHandler class LogHandler(ContentHandler): def startElement(self,name): if name=='a': #self.do_this() parse(xmlLog.xml,LogHandler()) From roy at panix.com Tue Mar 7 08:19:29 2006 From: roy at panix.com (Roy Smith) Date: Tue, 7 Mar 2006 13:19:29 +0000 (UTC) Subject: Checking function calls References: Message-ID: Fredrik Tolf wrote: >If I have a variable which points to a function, can I check if certain >argument list matches what the function wants before or when calling it? > >Currently, I'm trying to catch a TypeError when calling the function >(since that is what is raised when trying to call it with an illegal >list), but that has the rather undesirable side effect of also catching >any TypeErrors raised inside the function. Is there a way to avoid that? The only way is to read the documentation for the function (or, the source code). Can you be a little more specific about what you're trying to do? Can you post your code? From duncan.booth at invalid.invalid Fri Mar 17 10:53:18 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2006 15:53:18 GMT Subject: Counting nested loop iterations References: <47vvhjFhb3hqU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> Which is utterly counter-intuitive, the opposite of Perl, and remains >> one of the most confusing and surprising things I have encountered in >> Python so far. > > AFAIK stems from mathematics where you write things like > > {y | \forall x \in X : \forall y \in x } > > And so many people consider it pretty natural/intuitive. After all, we > read from left to right, and making something depend from something > yet to be introduced is counter-intuitive in my book. YMMV though. > I think the problem is that y is used before the loop which creates it, but x is used after the loop which creates it. People can cope with the expanded loop form where everything it is used after it is introduced, and it would appear that they also cope well with the perl way of doing everything backwards, but moving the last element to the front while keeping everything else in the 'correct' order seems to confuse a lot of people. Oh well, just wait until Python 2.5 comes out and we get people complaining about the order of the new if statement. From rurpy at yahoo.com Fri Mar 31 16:53:30 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 31 Mar 2006 13:53:30 -0800 Subject: Doc suggestions (was: Why "class exceptions" are not deprecated?) In-Reply-To: References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com> <1143574346.354680.136060@i39g2000cwa.googlegroups.com> <1143765024.109931.96090@j33g2000cwa.googlegroups.com> Message-ID: <1143842010.610324.16710@t31g2000cwb.googlegroups.com> Ed Singleton wrote: > On 30 Mar 2006 16:30:24 -0800, rurpy at yahoo.com wrote: > > > > What are you saying? Ideas must come only from those > > with the time and skill to implement them? No one else > > need apply? > > Ideas can come from anyone and they do come from anyone all the time, > and as such they are fairly worthless unless acted upon. That is pretty obvious. The question is about who does the acting. Your position seems to be that only those that act have a right to present ideas. This is bogus for a whole bunch of reasons: - It is exceptional case when people go off and do something by themselves and produce good results. The power of free software lies in its collaborative nature. - Many changes are too big or pervasive, and need cooperation from many people (or at least agreement.) - Even small changes often need help from others (sometimes just information) - People can have a good idea, even if they are not capable of implementing it. - This is particularly true in documentation and ui where the lowly user is, in many respects, the expert. - Even if an idea is not good, it can start someone else thinking and their idea may be good. - Without outside ideas and critisism the core development group can become "inbred" and loose touch with the user community. - Putting restrictions on who can contribute ideas is often just human psycological desire for exclusion and control. - Using an open forum like usenet means you *will* get ideas and critisism from "unworthy" people. Group think and intimidation can reduce but not eliminate it. > If you want > someone else to do the acting upon for you, for free This is what is tripping you up. You interpret my critisism as a demand that "you" (plural) do something. First it is not a demand. It is (to use your terminology below), a gift. You want to ignore it? Fine. You want to delete all documentation and say, "well that will teach to complain!" Fine. You want to add it to actual or mental list of things to think about. Fine. You want to encourage people to discuss it leading (hopefully) to someone doing something about it? Fine. I was once involved periperaly in the UI part of a software project. The hardest part was finding out what problems users had with the ui and documentation. The company had a bunch of very expensive engineers and tech writers sit down with a group of potential users (also expensive), for several weeks, studying what problems the users had, what was confusing or not clear, what was liked and not liked. Obtaining this info was very expensive. The results were excellent. I suggest when that kind of info is offered to you for free on usenet, you might want to take advantage of it. > (and probably for no thanks), Do you think you know me well enough from a handful of usenet postings to conclude that? > then it has to be one hell of an amazing idea that no one > else has ever had (which, trust me, you won't have, and neither, > probably, will I). I definately won't, but you (with low probability) might? Well, at least your digs are more subtle than Fredrik's. :-) > Everyone knows how to improve open source software, but what good is > that to anyone? Making the improvements is worth hell of a lot and > that's why the people who do develop a lot of kudos in the community > (it's about the only payment they get for it, and they do deserve it). Of course they do. But that does not extend to being silent about problems. > If you have an idea, then good for you, but make some small attempt to > do something about it yourself. Prehaps you missed my post where I suggested a concrete textual correction. And offered to change the source myself if the developers are too busy? Or perhaps you missed the patches I submitted to correct other issues with the docs that have been sitting there for four months? > I'm not much of an expert in anything yet, but I had an idea, and then > managed to put the documents in a wiki, which was at least trying to > do something. Fredrik beat me to it and did a much better job, but > even so I feel quite proud that I did something and tried to move > things on, rather than just post to a mailing list and hope someone > else does it. I'm sorry, I don't buy your "just do it" philosophy. For one, its often not possible. (E.g. my offer to make a doc correction if given cvs access.) For another, "just do it" without thought, discussion with others, etc will most often lead to a half-assed solution, or a waste of time because everyone else rejects the work. And you are misrespresenting me by saying "...just post to a mailing list and hope someone else does it." I offered in many previous posts and the post you responded to, to actually do some work. > > Whenever anyone criticizes anything about free software > > there are three automatic responses: > > > > 1. You are an idiot if you can't understand / have a problem with that. > > 2. Its free so you should be grateful and shutup. > > 3. You have the source, change it yourself, you lazy whiner. > > Whenever people are rude to you, it's quite useful to stop and think > why. Quite often you'll find that it's something you're doing wrong. Yup, Continual self examination is a good thing. > If it happens every single time you make a criticism, then it's > definitely something you are doing wrong. You are flat wrong here. A cursory look at any history book will show dozens of examples where people who stood up for what came to be seen as right, had to do so alone, against critisism, personal attacks, and sometimes at the cost of their lives. (No, people on usenet are not substantialy different than people in history books) (No I am not a crusader or see myself as one. I just do not give a rat's ass about following the party line.) >... > If someone came to me with a gift, should I take it and start pointing > out all it's flaws and demanding that they fix the flaws? Bad analogy. Python is not a "gift" that was given to me. Guido did not get up one morning and say, "I think I will develop a new language for Rurpy". I doubt he ever thought, "I think I'll develop a new langauage for all my friends, and make the world a better place". I guess that he and the other Python contributors contribute for the same reasons most open source developers do, dissatifaction with current langauges, a desire to improve their own environment, a desire for status, a desire to see their ideas put into practice. (Another darker motivation in some projects, not Python I think, is, sadly, a desire to use open source to make lots of money by getting free labor.) Of course I don't know Guido et.al. so this is speculation, but there is a lot written about motivation in the free software world in general. That it is not a gift can also be confirmed on the Python.org website: Python Success Stories Python is part of the winning formula for productivity, software quality, and maintainability at many companies and institutions around the world. The trouble is, you want it both ways. You want to present Python as a industrial strength language on a par with commercial offerings, but when someone looks at Python with the same critcal eye they would look at a commercial product with, you switch back to the "it's a gift, how dare you criticize it!" mode. It you want Python to be considered a serious "real world" language, you'd do better to argue factually and credibly that x is not a problem, or admit it is a problem and be open to suggestions about how to fix it. From onurb at xiludom.gro Thu Mar 30 04:44:37 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 30 Mar 2006 11:44:37 +0200 Subject: does python could support sequence of short or int? In-Reply-To: <1143703009.628171.203020@i39g2000cwa.googlegroups.com> References: <1143703009.628171.203020@i39g2000cwa.googlegroups.com> Message-ID: <442ba8c6$0$9657$636a55ce@news.free.fr> momobear wrote: > hi, is there a way to let python operate on sequence of int or short? > In C, we just need declare a point, I assume you mean a 'pointer'. > then I could get the point value, > just like: > short* k = buffer, //k is a point to a sequence point of short. > short i = *k++, > but python is a dynamic language, > a = buffer > i = ? I don't know how to continue, what's a? a seems to be a str? > You'd probably get better answers by exposing the problem you're trying to solve instead of what you think is the solution Anyway, if you want a list if integers, just put integers into a list and iterate over that list: buffer = [1, 2, 3, 42] for i in buffer: do_something_with(i) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From hosalo at _NO_SPAM_gmail.com Sun Mar 19 10:04:59 2006 From: hosalo at _NO_SPAM_gmail.com (Heikki Salo) Date: Sun, 19 Mar 2006 15:04:59 GMT Subject: C-API: A beginner's problem In-Reply-To: References: Message-ID: Fabian Steiner wrote: > What did I do wrong? As I am quite new to C, I probably made many > mistakes, so please feel free to correct me. The following line: > for (i = 0; i <= seqlen; i++) { Should be "for (i = 0; i < seqlen; i++) {". Otherwise the last assignment will be out of bounds and probably corrupts heap. From gongcheng_g at hotmail.com Thu Mar 23 09:23:33 2006 From: gongcheng_g at hotmail.com (ChengGong) Date: 23 Mar 2006 06:23:33 -0800 Subject: Probelem about image size and dimensions In-Reply-To: <48fj9iFjnjhpU1@uni-berlin.de> References: <1143109000.672508.175070@t31g2000cwb.googlegroups.com> <48fbg4Fjqn9hU1@uni-berlin.de> <1143111286.875298.277290@z34g2000cwc.googlegroups.com> <48fdmpFk0bbbU1@uni-berlin.de> <1143114499.640227.267150@u72g2000cwu.googlegroups.com> <48fj9iFjnjhpU1@uni-berlin.de> Message-ID: <1143123813.097426.41180@e56g2000cwe.googlegroups.com> Hi Diez, They do not allow me to do what u said above. so I do not have any idea what is supposed to do. however i am think that if I can get the id of the image, i have chance to modify it. This is what i programed but it is an empty page, I but it in images folder

File Library

File Last Modified
is there any mistake? How ever thank you alot Diez. Your comments and suggestion are helpful. P.S. i am doing my internship in a commercial company:(, create external method is not allowed in my situation Cheng From ruby at no.spam Thu Mar 16 19:36:20 2006 From: ruby at no.spam (Michal Kwiatkowski) Date: Fri, 17 Mar 2006 01:36:20 +0100 Subject: My Generator Paradox! References: <1142554666.740989.303350@p10g2000cwp.googlegroups.com> Message-ID: vbgunz wrote: > def generatorFunction(sequence=['item1', 'item2', 'item3']): > for item in sequence: > yield item > > yieldedValue = generatorFunction() You're creating an iterator here and binding it to name yieldedValue (which is bogus, it should be named valueGenerator or sth like that). > '''this seems to work perfectly.''' > print '-' * 32 > print yieldedValue # > print yieldedValue.next() # item1 > print yieldedValue.next() # item2 > print yieldedValue.next() # item3 You're calling your iterator's next() method getting all of values, as expected. > '''this is where things don't make any sense!''' > print '-' * 32 > print generatorFunction() # You're creating a new iterator here. > print generatorFunction().next() # item1 Another anonymous iterator gets created here. Instantly its next() method is called, yielding first value. > print generatorFunction().next() # item1 And so on... > generatorFunction() is a call (obvious) when calling the second set, I > am resetting the iteration and this explains why I only and always get > item1. > > ok. *but* why in the world does the first set of calls work? > technically, isn't yieldedValue == generatorFunction() on a name > basis? I mean isn't the following technically the same? > > generatorFunction() > yieldedValue = generatorFunction() Well, first statement creates new iterator which is garbage collected right away (as it has no bindings). Second statement creates an iterator and binds it to name yieldedValue. Then it can be used as typical iterator. Calling yieldedValue.next() just calls method of the same iterator you've created a moment ago. It's still the same object. The difference is like the difference between following two lines: list() # creating a new list new_list = list() # creating a new list and binding its name So, rewriting your example from generator to dictionary objects: alist = [1, 2, 3, 4, 5] print alist # [1, 2, 3, 4, 5] print alist.pop() # 5 print alist.pop() # 4 print alist.pop() # 3 print [1, 2, 3, 4, 5] # [1, 2, 3, 4, 5] print [1, 2, 3, 4, 5].pop() # 5 print [1, 2, 3, 4, 5].pop() # 5 print [1, 2, 3, 4, 5].pop() # 5 Remember that generator is an object and you'll be fine. 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 scott.daniels at acm.org Sat Mar 18 16:21:37 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 18 Mar 2006 13:21:37 -0800 Subject: Have you ever considered of mousing ambidextrously? In-Reply-To: References: <1142660417.662387.73350@j33g2000cwa.googlegroups.com> Message-ID: <441c779a$1@nntp0.pdx.net> Roy Smith wrote: > I never understood why people switch mouse buttons. I'm left handed, so I > put the mouse on the left side of my keyboard. It never occurred to me to > flip the buttons around. Well, I switch 'em because the "forefinger is primary" is ingrained. > When somebody right handed sits down at my keyboard, I often see them > trying to avoid using the mouse (using arrow keys, control keys, anything > to avoid mousing). I just pick up the mouse and move it over to the right > side for them, and then they often say, "But, the buttons are backwards > now". Apparently most right handers *expect* that I, as a sinister mouse > user, have changed the buttons. Why? > > Of course, I grew up (and still prefer) the Mac, where there *is* only one > button. I grew up on 3-button mice, and later worked with people used to the original optional chord pad, so I find the Apple "users can't count past one" attitude strange. With the chord pad and three-button mouse, you could fill in forms without touching the keyboard. http://www.cedmagic.com/history/first-computer-mouse.html --Scott David Daniels scott.daniels at acm.org From klachemin at comcast.net Sun Mar 26 14:59:38 2006 From: klachemin at comcast.net (Kamilche) Date: 26 Mar 2006 11:59:38 -0800 Subject: image reduction script In-Reply-To: References: <%cUUf.2478$fS6.24@dukeread11> <1143353989.469397.41690@j33g2000cwa.googlegroups.com> Message-ID: <1143403178.019840.145620@j33g2000cwa.googlegroups.com> Be sure and use mode = P instead of RGB, like you have in your other code. P is for palettized images. Don't palettize if you're storing as JPG, only if you're storing as PNG or some other format that can handle 256 color images. From hancock at anansispaceworks.com Sat Mar 11 05:13:44 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 11 Mar 2006 04:13:44 -0600 Subject: put multiple condition in if statement In-Reply-To: <1142053977.812201.57640@i39g2000cwa.googlegroups.com> References: <1142053977.812201.57640@i39g2000cwa.googlegroups.com> Message-ID: <20060311041344.0e758e9c@samwise.anansi> On 10 Mar 2006 21:12:57 -0800 Allerdyce.John at gmail.com wrote: > How can I put multiple condition in if statement? > I try this, but I can't get that to work. > > if ( (str != " ") && (str != "") ): if s!=' ' and s!='': 1) logical operators are words 2) don't overload standard type names this is actually better style: if s not in (' ', ''): -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From greg at cosc.canterbury.ac.nz Wed Mar 1 04:26:10 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 01 Mar 2006 22:26:10 +1300 Subject: PEP 354: Enumerations in Python In-Reply-To: References: <87accdplbj.fsf@rose.polar.local> <7xmzgdtjl0.fsf@ruckus.brouhaha.com> <4402AB7F.7070804@REMOVEMEcyber.com.au> <7xzmkdxkce.fsf@ruckus.brouhaha.com> Message-ID: <46l8fbFbnfgeU1@individual.net> Steven D'Aprano wrote: > You can't shell an egg that isn't there. Yesterday upon the stair I shelled an egg that wasn't there. I'd shell the thing again today If only I could find a way. -- Greg From grante at visi.com Mon Mar 13 17:09:58 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 13 Mar 2006 22:09:58 -0000 Subject: Is this possible in Python? References: <1142238871.199749.243470@p10g2000cwp.googlegroups.com> <1142282467.270698.142780@p10g2000cwp.googlegroups.com> Message-ID: <121brdm92tbacce@corp.supernews.com> On 2006-03-13, alainpoint at yahoo.fr wrote: > Hello again, > I am disappointed. Yea, life's like that. Sucks, eh? -- Grant Edwards grante Yow! ... The waitress's at UNIFORM sheds TARTAR SAUCE visi.com like an 8" by 10" GLOSSY... From citizenkahn at gmail.com Thu Mar 23 14:50:58 2006 From: citizenkahn at gmail.com (citizenkahn) Date: 23 Mar 2006 11:50:58 -0800 Subject: Find Paths in log text - How to? Message-ID: <1143143458.856702.112890@i40g2000cwc.googlegroups.com> I am trying to parse a build log for errors. I figure I can do this one of three ways: - find the absolute platonic form of an error and search for that item - create definitions of what patterns describe errors for each tool which is used (ant, MSDEV, etc). - rework the build such that all the return codes for all 3rd party are captured and logged using my own error description The return code method has a high level of effort attached and spreads the responsibility for the task quite widely unless I can write a little command pattern like wrapper script (which is a possibility). Still it would mean all of the 100s of calls to tools would have to wrapped and if any place a developer changed this, the build would leak errors. The relativism/definition based approach means that I must be sure to capture all error cases which may prove difficult and false negatives are a really dangerous problem. In the Platonic/absolutist camp, I could define an error as an instance of a word or phrase from the "bad list" that is not in a filename or path. Bad List: [error, fatal, killed, not found]. Were I to go this way, I'd be faced with a major problem: in a world where symbols and whitespace can be included in a path how can I extract a path from a line of text? Ugly Valid Paths: C:\Program Files\A File Named Error .txt /usr/#a file named error #.txt This means that determining the boundaries of a path is non trivial. FileNames: Many build tools list filenames without their full path. All of my product's files are ., so that is a pattern that I might be able to locate .+\..+ perhaps Paths: on windows all of my paths will start with [A-Z]:\ or \\ on unix the will tend to start with ./ or /. Finding the starting point is not too difficult, but its that ending that's hard I could generate a substring for each of the starting types and then look at what came before. for sep in [letterStart, uncStart, unixrootedStart, unixpwdStart]: # create sub string prePath = line.split(elem)[0] checkForBadWords(prePath) I could then split the postPath segment on the os.sep and the check for unlikely cases in the list elements - double spaces within a path element - symbol characters within an element (although this is a little dicey) Since I am parsing the log on the system on which it was generated, for each path I could do an os.path.exists on the potential path. If someone happens to know of a good method of extracting weird paths out of logs, I'd be interested in hearing about it. From __peter__ at web.de Sat Mar 11 03:39:48 2006 From: __peter__ at web.de (Peter Otten) Date: Sat, 11 Mar 2006 09:39:48 +0100 Subject: Performance impact of using decorators References: <1142003515.886709.290360@j33g2000cwa.googlegroups.com> Message-ID: vinjvinj wrote: > I'm building an application with cherrypy and have started using > decorators quite extensively. A lot of my exposed functions look like: > > @expose > @startTransactrionAndBuildPage > @partOfTabUi(tabId) > @convert(arg1=int, arg2=str) > def do_main_page(self, arg1, arg2): > some code > > > I've become really fond of decorators and use them quite a lot. I've > also ready that function calls are expensive in python. In the above > example, does the interpreter call 5 different functions? A typical function calls a few other functions already, so three extra function calls (I suppose expose just sets an attribute) shouldn't matter much. You shouldn't even start rewriting your code unless you have identified do_main_page() as a performance bottleneck. In a web app, candidates would be functions that are called hundred or thousand times per rendered page rather than once. Does do_main_page() render a complete page? Forget optimizing three function calls away. You will see no effect. Peter From cdunn2001 at gmail.com Mon Mar 6 17:26:09 2006 From: cdunn2001 at gmail.com (cdunn2001 at gmail.com) Date: 6 Mar 2006 14:26:09 -0800 Subject: Need help initializing a list or tuple. In-Reply-To: <1141674074.417716.158780@p10g2000cwp.googlegroups.com> References: <1141664498.539402.43160@e56g2000cwe.googlegroups.com> <1141667358.694629.91840@j52g2000cwj.googlegroups.com> <1141674074.417716.158780@p10g2000cwp.googlegroups.com> Message-ID: <1141683969.069542.23190@j52g2000cwj.googlegroups.com> # Nested list comprehensions act like real for loops: >>> a = [[None for i in range(3)] for j in range(3)] >>> a [[None, None, None], [None, None, None], [None, None, None]] >>> a[0][0] = 5 >>> a [[5, None, None], [None, None, None], [None, None, None]] # Side-effect: i and j will be changed. # Another way (much less clear to my eyes): >>> a = map(lambda x: map(lambda x: None, range(3)), range(3)) >>> a[0][0]=5 >>> a [[5, None, None], [None, None, None], [None, None, None]] From mandelin at cs.berkeley.edu Thu Mar 30 13:43:17 2006 From: mandelin at cs.berkeley.edu (Dave Mandelin) Date: 30 Mar 2006 10:43:17 -0800 Subject: Quick Question regarding Frames In-Reply-To: <1143655614.211630.148110@z34g2000cwc.googlegroups.com> References: <1143555706.435922.309210@g10g2000cwb.googlegroups.com> <1143571941.731740.228960@g10g2000cwb.googlegroups.com> <1143577846.750248.107300@j33g2000cwa.googlegroups.com> <1143654936.844212.283780@i40g2000cwc.googlegroups.com> <1143655614.211630.148110@z34g2000cwc.googlegroups.com> Message-ID: <1143744197.409774.17210@e56g2000cwe.googlegroups.com> I'm glad to have helped. Good luck with your project. -- Want to play tabletop RPGs over the internet? Check out Koboldsoft RPZen: http://www.koboldsoft.com From mbukhin at gmail.com Wed Mar 29 02:40:18 2006 From: mbukhin at gmail.com (mbukhin at gmail.com) Date: 28 Mar 2006 23:40:18 -0800 Subject: FTP not Returning (Python on Series 60 Nokia) Message-ID: <1143618018.661424.234510@v46g2000cwv.googlegroups.com> I'm using the ftp library (layer on top of sockets) to transfer files from a series 60 to an ftp site. everything works fine, the whole file gets uploaded but the command never returns! so i call: ftp.storbinary('STOR ' + filename,F,1024) # store the image which does this: def storbinary(self, cmd, fp, blocksize=8192): '''Store a file in binary mode.''' self.voidcmd('TYPE I') conn = self.transfercmd(cmd) while 1: buf = fp.read(blocksize) if not buf: break conn.send(buf) conn.close() return self.voidresp() and the 'while 1' never stops. That's my guess anyway. When I run this in interactive bluetooth mode the storbinary command just hangs (though the file ends up on the server). i've tried a bunch of different things, counters, comparisons, everything. there's a signal library in python but i don't think it's supported in mobile devices. any suggestions? thanks! From db at test.nl Fri Mar 17 10:54:30 2006 From: db at test.nl (Duikboot) Date: Fri, 17 Mar 2006 16:54:30 +0100 Subject: Python train spotting doodle In-Reply-To: <4803qgFhdb33U1@uni-berlin.de> References: <4803qgFhdb33U1@uni-berlin.de> Message-ID: http://apipes.blogspot.com/2005/01/choose-python.html I have printed on my office wall too. Duikboot Diez B. Roggisch wrote: > Hi, > > a year or two ago, somebody posted a link to an image he created. It was > basically a remake of the famous trainspotting-poster that begins all > sentences with "Choose ..." > > Back then I printed it out and hung it on my office wall. New emplyoer, > empty wall, crying for a printout... > > But I didn't find it - any pointers are greatly appreciated. > > regards, > > Diez From mrstephengross at hotmail.com Fri Mar 10 14:43:27 2006 From: mrstephengross at hotmail.com (mrstephengross) Date: 10 Mar 2006 11:43:27 -0800 Subject: McMillan installer on solaris - complains about missing .pkg file Message-ID: <1142019806.961777.234210@u72g2000cwu.googlegroups.com> I'm trying to get the mcmillan installer utility to generate a standalone executable for me. I've gotten to work--almost!--but still have one problem. After running Installer's Build.py on my script/spec, it appears to work. I go into the directory generating by Build.py and run my program. It works! Then I copy my program (foo) to a different directory and try to run it there. It complains that: "Cannot open self /home/sgross/foo or archive /home/sgross/foo.pkg". Do I have to distribute the .pkg file with the executable? If so, is there a way around this? I want to distribute a single, standalone executable. Thanks, --Steve (mrstephengross at hotmail.com) From jeffrey at fro.man Wed Mar 22 13:38:20 2006 From: jeffrey at fro.man (Jeffrey Froman) Date: Wed, 22 Mar 2006 10:38:20 -0800 Subject: Server.sendmail with no "to_addrs" parameter. References: <1143026321.129185.109310@j33g2000cwa.googlegroups.com> <12231h0q5531se8@corp.supernews.com> <1143050142.925925.65960@j33g2000cwa.googlegroups.com> Message-ID: <12236cqqf20gc7f@corp.supernews.com> EdWhyatt wrote: > But are you serious about that RFC Compliant thing? RFC 2822 obsoletes RFC 822, and I don't know of any specification in RFC 2822 that requires an email address to be present in the To: header. My mail seems to generally work fine without a To: header. I haven't memorized RFC 2822 though, so you may want to read it yourself if you're concerned ;-) Jeffrey From scott.daniels at acm.org Sun Mar 19 10:06:22 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 19 Mar 2006 07:06:22 -0800 Subject: Python 2.5 Schedule In-Reply-To: <1142768924.634611.50400@e56g2000cwe.googlegroups.com> References: <1142667600.257048.315910@z34g2000cwc.googlegroups.com> <441c79d5$1@nntp0.pdx.net> <1142768924.634611.50400@e56g2000cwe.googlegroups.com> Message-ID: <441d7122$1@nntp0.pdx.net> Gregory Petrosyan wrote: > P.P.S. are there any experiments with compiling CPython with Intel's > compiler? Yup, the (older) Intel compiler was quite effective for 2,2 and 2.3 (at least), and I think at least one distro was built with it. -- -Scott David Daniels scott.daniels at acm.org From grante at visi.com Wed Mar 15 10:11:44 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 15 Mar 2006 15:11:44 -0000 Subject: MS word document generator References: <1142413907.226088.190740@j33g2000cwa.googlegroups.com> Message-ID: <121gblgb57p39e9@corp.supernews.com> On 2006-03-15, Raja Raman Sundararajan wrote: > Is there any nice library to generate word documents using Python. I find the following works well for me: f = open("file.doc") f.write("Hello there.\n") f.write("How are you?\n") f.close() > As of today I am generating a HTML document and then open it > with MS Word. But the problem is that I am not able to control > the pages in the document and as a result of it the output > looks terrible. If you want fancier formatting that available in my example code, I'd look for a library to generate RTF. Something like this perhaps (I haven't tried it yet): http://pyrtf.sourceforge.net/ RTF is far more portable that whatever ".doc" format-du-jour happens to be in vogue in Redmond. > I have been using reportlab's platypus to generate PDF > documents. Its a nice application which allows controlling > segments of the pages programatically. > > I was wondering if there was any library as reportlab to > generate word documents. -- Grant Edwards grante Yow! ... I have read the at INSTRUCTIONS... visi.com From mtobis at gmail.com Fri Mar 24 21:55:51 2006 From: mtobis at gmail.com (Michael Tobis) Date: 24 Mar 2006 18:55:51 -0800 Subject: Remove integer from float number In-Reply-To: <1143184126.831239.214460@t31g2000cwb.googlegroups.com> References: <1226859e35171a3@corp.supernews.com> <1143184126.831239.214460@t31g2000cwb.googlegroups.com> Message-ID: <1143255351.839890.81910@e56g2000cwe.googlegroups.com> I think you ought to make your own class and define some of the special methods. mt From forum at anton.e4ward.com Fri Mar 31 05:00:00 2006 From: forum at anton.e4ward.com (Anton81) Date: Fri, 31 Mar 2006 12:00:00 +0200 Subject: Connecting to gnuplot with Popen? References: Message-ID: > Hi Anton, > > here is a little snippet using os.popen: Unfortunately I'm having more problem getting the output from Gnuplot, which I'd like to examine for error messages and settings of options. Anton From bencvt at gmail.com Thu Mar 30 19:18:50 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 30 Mar 2006 16:18:50 -0800 Subject: Simple py script to calc folder sizes In-Reply-To: <1143700292.340111.128340@i40g2000cwc.googlegroups.com> References: <1142983179.378155.92340@v46g2000cwv.googlegroups.com> <1143700292.340111.128340@i40g2000cwc.googlegroups.com> Message-ID: <1143764330.069364.147600@e56g2000cwe.googlegroups.com> Caleb Hattingh wrote: > Your code works on some folders but not others. For example, it works > on my /usr/lib/python2.4 (the example you gave), but on other folders > it terminates early with StopIteration exception on the > os.walk().next() step. > > I haven't really looked at this closely enough yet, but it looks as > though there may be an issue with permissions (and not having enough) > on subfolders within a tree. You're quite correct. Here's a version of John's code that handles such cases: import warnings def foldersize(fdir): """Returns the size of all data in folder fdir in bytes""" try: root, dirs, files = os.walk(fdir).next() except StopIteration: warnings.warn("Could not access " + fdir) return 0 files = [os.path.join(root, x) for x in files] dirs = [os.path.join(root, x) for x in dirs] return sum(map(os.path.getsize, files)) + sum(map(foldersize, dirs)) There's also another bug in the prettier() function that barfs on empty directories, as it's taking the log of 0. The fix: exponent = int(math.log(max(1, bytesize), 1024)) --Ben From robert.kern at gmail.com Sat Mar 18 23:47:44 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 18 Mar 2006 22:47:44 -0600 Subject: Need design advice. What's my best approach for storing this data? In-Reply-To: <1142742022.415092.243210@g10g2000cwb.googlegroups.com> References: <1142615283.733346.74260@i40g2000cwc.googlegroups.com> <1142742022.415092.243210@g10g2000cwb.googlegroups.com> Message-ID: Mudcat wrote: > In doing a little research I ran across PyTables, which according to > the documentation does this: "PyTables is a hierarchical database > package designed to efficiently manage very large amounts of data." It > also deals with compression and various other handy things. Zope also > seems to be designed to handle large amounts of data with compression > in mind. > > Does any know which of these two apps would better fit my purpose? I > don't know if either of these has limitations that might not work out > well for what I'm trying to do. I really need to try and compress the > data as much as possible without making the access times really slow. PyTables is exactly suited to storing large amounts of numerical data aranged in tables and arrays. The ZODB is not. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From fredrik at pythonware.com Fri Mar 10 11:43:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 10 Mar 2006 17:43:10 +0100 Subject: [How to change redirect stderr?] References: Message-ID: "Moretti" wrote: > I would like to be able to change the standard error path. (I'm not sure path is the right word here, really, but never mind...) > How can I do this in a script if I want to send error messages to /dev/null > by example ? if you're talking about things that Python prints to stderr, all you need to do is to replace sys.stderr with something more suitable: import sys sys.stderr = open("/dev/null", "w") or, more portable: class NullDevice: def write(self, s): pass sys.stderr = NullDevice() if you want to redirect both things printed via sys.stderr and things printed to stderr at the C level, you need to redirect the STDERR file handle. here's one way to do that: import os, sys sys.stderr.flush() err = open('/dev/null', 'a+', 0) os.dup2(err.fileno(), sys.stderr.fileno()) hope this helps! From correia_j at KILLTHIShotmail.com Sat Mar 25 19:21:46 2006 From: correia_j at KILLTHIShotmail.com (J Correia) Date: Sun, 26 Mar 2006 00:21:46 GMT Subject: Beginner's question: executing scripts under Win XP pro References: <7bna22hp2bj8svrmbof0n6jg6q58oa27i6@4ax.com> Message-ID: "Scott Souva" wrote in message news:7bna22hp2bj8svrmbof0n6jg6q58oa27i6 at 4ax.com... > Your script may be working properly, but XP simply removes the window > after the script runs. Here is a simple fix that will stop at the end > of the script and leave the Command window open: > > print "Hello World" > raw_input() That'll work (it waits for input from the user, and, as soon as it receives it shuts down the window). Another way to do it is instead of doubleclicking on the script, open a command prompt window (Start>Run>cmd OR Start>Programs>Accessories>Command Prompt) then type 'python test.py' at the prompt. Now the window stays open until you specifically close it and you can rerun the script many times. HTH, JC From Mark.Warburton at gmail.com Fri Mar 17 14:34:19 2006 From: Mark.Warburton at gmail.com (Mark Warburton) Date: 17 Mar 2006 11:34:19 -0800 Subject: Is there no end to Python? References: <1142622194.560240.4330@j52g2000cwj.googlegroups.com> Message-ID: <1142624059.926159.132000@j52g2000cwj.googlegroups.com> John Salerno wrote: > > But isn't Python sort of known for the opposite, i.e. 'one simple way', > or something to that effect? Ha! I was thinking the same thing. But then I realized this only applies at the microscopic level. If you're doing something like reversing the order of the elements in a list, there aren't many different ways to do it. On the other hand, if you're looking at macroscopic task like writing a flight simulator, there are many many different ways to approach it. A pythonic language limits you at the microscopic level but not the macroscopic! This way the code is readable by anyone (including you!) and you are free to dream up any algorithms you like. -- Mark Warburton Ottawa, Canada From xivulon at gmail.com Mon Mar 27 14:10:05 2006 From: xivulon at gmail.com (ago) Date: 27 Mar 2006 11:10:05 -0800 Subject: win32com: error 80004005 Message-ID: <1143486605.135183.51180@j33g2000cwa.googlegroups.com> I am trying to make the win32com HelloWorld server work with a VBA client but I get: Run-time error '-2147467259(80004005)': Automation error Unspecified error I googled for the error but the suggested solutions (commenting out _reg_class_spec_ and putting the server on the python path) do not seem to make any difference (to be precise, unless I comment out _reg_class_spec_ I cannot register the server at all) . The server works under the python client but not on excel vba. I also tried to debug with win32traceutil.py but I can only see the trace when using the python client, not with excel. Any hint would be appreciated. ### PYTHON SERVER ### class HelloClass: _reg_desc_ = "Python Test COM Server" _reg_clsid_ = "{91281AFC-25DF-4400-8868-FDBFCA2612A2}" _reg_progid_ = "Python.HelloHello" _public_methods_ = ['Hello'] def __init__(self): pass def Hello(self): return "Hello" if __name__ == "__main__": import win32com.server.register import sys #sys.argv.append("--debug") win32com.server.register.UseCommandLine(HelloClass) ### PYTHON CLIENT (WORKS) ### import win32com.client obj = win32com.client.Dispatch('Python.HelloHello') print obj.Hello() ### VBA CLIENT (ERROR 80004005 WHEN EXECUTING "CreateObject") ### Public Sub test() Dim obj As Object Set obj = CreateObject("Python.HelloHello") MsgBox obj.Hello("ago") End Sub From fuzzyman at gmail.com Wed Mar 29 10:18:27 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Mar 2006 07:18:27 -0800 Subject: Validating Syntax only with PyParser_SimpleParseString ? In-Reply-To: <1143637397.818081.11110@g10g2000cwb.googlegroups.com> References: <1143637397.818081.11110@g10g2000cwb.googlegroups.com> Message-ID: <1143645507.309152.69000@e56g2000cwe.googlegroups.com> gaston.gloesener at web.de wrote: > I am seeking for a method to parse single lines of Python code (infact > they are only formulas, so I generate a line like RESULT=). I > do only want to know if the syntax is correct and if there is an error > best would be to know where. > > I did find PyParser_SimpleParseString which does return a node > structure. If there is an error it seems to return NULL, while I did > not find this documented. > > Th eproblem with this is that first I do not get th elopcation of the > syntax error, and second I don't know what is the proper method to free > the node structure after I got it, since I will not use it. Or is there > any better method doing this anyway. > A better way might be to use the standard library compiler module. A file called cptools.py (part of the cherrypy project) has a very simple example called 'unrepr' which shows how to do it. I only have restricted internet access or I would find the URL for you (sorry). Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Environment: Windows / Borland C++ From beyerxyzzy at acm.org Fri Mar 17 10:58:26 2006 From: beyerxyzzy at acm.org (Hugh Beyer) Date: Fri, 17 Mar 2006 15:58:26 GMT Subject: Pythong CGI scrips on Windows Server 2003 References: Message-ID: Tim Roberts wrote in news:g7r412ph71uveuj1abc9q2hp77kljkuhk1 at 4ax.com: > Hugh Beyer wrote: >> >>We are moving to a new server running Windows Server 2003 from existing >>servers runing Windows Server 2002 and IIS is giving us fits. > > Do you mean Windows 2000 Server? > > My experience with IIS has been universally bad. In each and every > case, I found it much more productive to disable IIS and install the > Win32 version of Apache. Yes, I mean Windows 2000 server. Python (and other CGI languages) ran on it without a problem. Perl fruns fine on the new server; Python doesn't. Hugh From greg.landrum at gmail.com Thu Mar 2 16:06:55 2006 From: greg.landrum at gmail.com (greg.landrum at gmail.com) Date: 2 Mar 2006 13:06:55 -0800 Subject: pickle and converting to new-style classes Message-ID: <1141333615.640536.317890@j33g2000cwa.googlegroups.com> Hi, I have a fairly sizable body of python code that I'm in the process of modernizing. One of the modernization steps is converting to use new-style classes, and this is leading to problems with pickle. What's happening is that part of the test suite for this code includes pickled instances of the classes I am modifying, attempting to unpickle these objects is generating errors in certain cases. A bit of sample code that shows the same problem: -------------------- import pickle # original class definition: class klass: def __init__(self,v): self._v=v # instantiate it: o = klass(3) # create a pickle (simulates our saved pickle on disc) pkl = pickle.dumps(o) # change the class definition (simulates changing the orginal # source): class klass(object): def __init__(self,v): self._v=v # this generates an error: n = pickle.loads(pkl) -------------------- There error I get is: Traceback (most recent call last): File "newclass.py", line 20, in ? n = pickle.loads(pkl) File "c:\Python23\Lib\pickle.py", line 1394, in loads return Unpickler(file).load() File "c:\Python23\Lib\pickle.py", line 872, in load dispatch[key](self) File "c:\Python23\Lib\pickle.py", line 1084, in load_inst self._instantiate(klass, self.marker()) File "c:\Python23\Lib\pickle.py", line 1074, in _instantiate value = klass(*args) TypeError: in constructor for klass: __init__() takes exactly 2 arguments (1 given) I realize I'm trying to do something a bit hackish, but re-generating these pickled instances from scratch would be a rather massive amount of work, so I'd really like to figure out some way to either "translate" the pickled instances to work with the new-style class definitions or to modify the class definition itself so that the pickles can be loaded (this would be preferable). Is this remotely possible? thanks, -greg From deets at nospam.web.de Fri Mar 17 10:59:11 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 17 Mar 2006 16:59:11 +0100 Subject: Counting nested loop iterations References: <47vvhjFhb3hqU1@uni-berlin.de> Message-ID: <4804mkFgp82nU1@uni-berlin.de> > I think the problem is that y is used before the loop which creates it, > but x is used after the loop which creates it. Well, you got me on that. Seems to be a matter of convention all the time. > People can cope with the expanded loop form where everything it is used > after it is introduced, and it would appear that they also cope well with > the perl way of doing everything backwards, but moving the last element to > the front while keeping everything else in the 'correct' order seems to > confuse a lot of people. > > Oh well, just wait until Python 2.5 comes out and we get people > complaining about the order of the new if statement. Sad, but true. But I'm a happy camper with list-comps and the new if-expression :) Diez From grahamd at dscpl.com.au Wed Mar 29 17:48:07 2006 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 29 Mar 2006 14:48:07 -0800 Subject: Apache and Python and Ubuntu References: <1143672083.347654.81330@v46g2000cwv.googlegroups.com> Message-ID: <1143672487.539116.306740@j33g2000cwa.googlegroups.com> msuem... at jjhill.org wrote: > I've create an Ubuntu Linux box, which comes pre-installed with Python > (I've added the libapache2-mod-python throught the app manager). I've > created .cgi and .py simple programs in the www root of apache. > > The problem is the programs just dump the contents to the browser in > plain text. Or, in the case of the .py files, I am prompted to > download the .py file. How can I get apache to recognize that it > should execute the .cgi script? > > Is there any special thing I need to do to apache to get it to know > that the python interpreter should be used for all .cgi files? You do not need mod_python if you want to use Python in traditional CGI scripts. Simply follow the Apache instructions for setting up CGI scripts and ignore mod_python all together. If you really did want to use mod_python, consider reading: http://www.dscpl.com.au/articles/modpython-001.html It provides more detailed instructions on getting a first test handler running. Graham From fredrik at pythonware.com Wed Mar 22 04:13:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Mar 2006 10:13:35 +0100 Subject: py web-app-frameworks without a rdbms... References: <1142989572.483475.158570@e56g2000cwe.googlegroups.com> Message-ID: venkatbo at yahoo.com wrote: > Of TurboGers & Django WAF candidates, which one would be easier to use > in an environment where the data/content doesn't come an RDBMS, but > from other server-side apps... Django is trivial to use for this (but you still want to use a DB together with the built-in admin interface for basic configuration stuff; sqlite may be good enough...) I haven't used TG myself, but it's probably just as easy. just pick a stable release of either one and get to work. From 3dbernard at gmail.com Tue Mar 21 16:49:50 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Tue, 21 Mar 2006 16:49:50 -0500 Subject: Problems writing to file In-Reply-To: <442069B3.6040500@islandtraining.com> References: <61d0e2b40603211247pf3bdb9cqf64469d4d77a7a5c@mail.gmail.com> <442069B3.6040500@islandtraining.com> Message-ID: <61d0e2b40603211349p23aaba77yc2648012fa9f0f77@mail.gmail.com> Hi Gary, That is actually what I do. Each time the program prints something to the file, it flushes the buffer. I also tried opening and closing the file, same result. I could indeed post the code. That is only a fraction of the program, as the log is managed through the Queue module: def __nodeLog( self, iCallerLevel, sJobID, sMsg ): """ The method checks for an override in loglevel given by command line argument. If such override has been set (using the 'loglevel' argument), then the command line value is used. ARGUMENTS: iCallerLevel (integer): level of verbosity to use, applies only to node type of logging sJobID (string): the JobID of the job, if applies sMsg (string): node line to print """ # Check if a log level was set through command line if 'loglevel' in dCmdLineArgs: # Log level set through command line, override any other log level sLogLevel = dCmdLineArgs[ 'loglevel' ] iLogLevel = int( sLogLevel ) else: iLogLevel = self.loglevel if iCallerLevel <= iLogLevel: # Forge line to print into node log sLine = '%s %s [jobid: %s]: %s\n' % ( NAME, time.ctime(), str( sJobID ), sMsg ) if self.printmsg == True: print sLine # Check if user specified extraction command line arguments for sArg, tValue in dCmdLineArgs.items(): if 'extractlog' in sArg: sLogLevel = tValue[0] sLogType = tValue[1] # Check if caller level is same as log level defined by the extract argument if str( iCallerLevel ) == sLogLevel: sExtractLogFile = os.path.join( self.NODELOGS, '%s_%s.log' % ( NAME, sLogType ) ) self.__output( sExtractLogFile, sLine ) self.__output( self.MAINLOGFILENAME, sLine ) def __output( self, sLogFile, sLine ): """ Try to write to the log file. ARGUMENTS: sLogFile (string): the log file sPrint (string): the line to print """ # Try 3 times to write to the output file for i in range(3): # Try to output the message try: oLogFile = file( sLogFile, 'a+' ) oLogFile.write( sLine ) oLogFile.close() return LOGOPSUCCESS except IOError: if i == 2: if self.printmsg == True: print '\nERROR > log.__output : All attempts to write to log file %s failed, latest updates will be lost.\n' % ( sLogFile ) return LOGOPFAILURE else: if self.printmsg == True: print '\nWARNING > log.__output : Attempt "%i" to write to log file %s raised IO Error, next attempt in %s seconds.\n' % ( i+1, sLogFile, self.LOGWAITTIME ) Thanks Bernard On 3/21/06, Gary Herron wrote: > Bernard Lebel wrote: > > >Hello, > > > >I have this strange problem. I have written a program that writes a > >log to a log file. > > > >To start the program (I'm on Linux Fedora Core 3), I used a service. > >This service runs a bash file, wich in turn runs the Python top > >program file. > > > >Sooner or later the program stops writing to the log file. I have > >absolutely no clue why would that happen. Since the output of the > >Python program is not redirected other than to this log file, I have > >no idea why it's doing this. But the Python process appears still > >alive and well! > > > >But the strange thing is that if I run the program directly from a > >bash shell, no problem whatsoever, the programs runs smoothly and > >never stops writing to the file, until I kill it. > > > > > >Any suggestion? > > > > > > > >Thanks in advance > >Bernard > > > > > Perhaps ... > > Output is normally buffered in memory until some threshhold is reached, > at which point the whole buffer is written, and the process repeats. If > your output quantity is small, and your impatience is high, you may be > declaring failure before the buffer fills and triggers a write. The > solution would be to call flush on the output file after each write (or > perhaps just wait more patiently). > > If the output is voluminous, then it's probably something else ... but I > don't know what. Perhpas you could post your code. > > Gary Herron > > From kent at kentsjohnson.com Mon Mar 6 07:28:02 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 06 Mar 2006 07:28:02 -0500 Subject: Python version of XMLUnit? In-Reply-To: References: <440b2ae2$1_2@newspeer2.tds.net> Message-ID: <440c2612_1@newspeer2.tds.net> Benjamin Niemann wrote: > http://www.logilab.org/projects/xmldiff > > You'd still have to integrate this into your test framework though... Thanks, that looks promising. > > And I'll have a look at XMLUnit - seem's like something I could use for my > current project ;) XMLUnit is *very* useful. For example here is a typical assertion error: [different] Expected attribute value '1500' but was '150' - comparing at /PageItem[1]/HotspotModelItem[1]/@height to at /PageItem[1]/HotspotModelItem[1]/@height Notice how it shows you exactly the error including XPath expressions to the node containing the error! In Jython I use unittest, not JUnit, so instead of subclassing XMLTestCase I call the static methods of XLMAssert from my test cases. Kent From s99999999s2003 at yahoo.com Tue Mar 28 22:36:53 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 28 Mar 2006 19:36:53 -0800 Subject: sending ctrl C to a process In-Reply-To: References: <1143598491.283734.37180@t31g2000cwb.googlegroups.com> Message-ID: <1143603413.043217.170540@e56g2000cwe.googlegroups.com> hi thanks for the reply.Actually, i should clarify what i am doing. the program's output will be displayed to a web browser using cgi, so there is no keyboard interrupt. The backend cgi script (python script) will have to send Ctrl-C to break the program. thanks From johnjsal at NOSPAMgmail.com Fri Mar 24 16:47:52 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 24 Mar 2006 21:47:52 GMT Subject: converting to a binary number? In-Reply-To: <1143230994.574344.181800@z34g2000cwc.googlegroups.com> References: <1143230994.574344.181800@z34g2000cwc.googlegroups.com> Message-ID: mensanator at aol.com wrote: > John Salerno wrote: >> I'm having some trouble finding a function that converts numbers >> (whether integer, hex, whatever) to its binary representation. Is there one? >> >> Thanks. > > Get the Gnu Multiple Precision library for Python module (Google GMPY). Thanks! From hancock at anansispaceworks.com Fri Mar 31 11:17:53 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 31 Mar 2006 10:17:53 -0600 Subject: Python plug-in In-Reply-To: <44299fc5$0$1148$7a628cd7@news.club-internet.fr> References: <44299fc5$0$1148$7a628cd7@news.club-internet.fr> Message-ID: <442D5631.2030503@anansispaceworks.com> toto wrote: >I'm trying to find some howto, tutorial in order to create a python program >that will allow plug-in programming. I've found various tutos on how to >write a plug-in for soft A or soft B but none telling me how to do it in my >own programs. Do you have any bookmarks ? > > There is more than one way to accomplish this, but one of the simplest is to provide a directory where plugins are loaded, and put an __init__.py in it which automatically finds files in the directory that conform to some standard, and imports them (or tries to). Here's a snippet from one of my projects: import sys, os from Operators import Operator, operate, Ops # Find and load all available plugin modules: operator_path = os.path.abspath(__path__[0]) for module_file in filter( lambda n: n[-3:]=='.py' and n not in ('__init__.py', 'Operators.py'), os.listdir(operator_path)): #print "Loading %s" % module_file f, e = os.path.splitext(module_file) __import__(f, globals(), locals(), []) (Operators.py is in the same directory and includes general purpose code that the plugins use -- I think it might be better design to put that in the parent directory. But that's awkward until Python introduces relative import notation -- supposed to be coming in v2.5). From kevin.dahlhausen at gmail.com Wed Mar 1 14:06:54 2006 From: kevin.dahlhausen at gmail.com (kpd) Date: 1 Mar 2006 11:06:54 -0800 Subject: Suggestions for documentation generation? Message-ID: <1141240014.302680.78850@z34g2000cwc.googlegroups.com> Hello, I have written a C++ library that I've then wrapped with Pyrex. Any suggestions to the best-in-class tool to create documentation for the libraries? I would love to document things in one spot (could be the code) and generate html and PDF from there. Doxygen (www.doxygen.org) looks to be about the best so far. Thanks, From johnjsal at NOSPAMgmail.com Wed Mar 29 14:34:03 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 29 Mar 2006 19:34:03 GMT Subject: python challenge question (string manipulation) In-Reply-To: References: Message-ID: John Salerno wrote: > It works, but is there a better way to shift the letters of the alphabet > for 'code'? I remember a method that did this for lists, I think, but I > can't remember what it was or if it worked for strings. Ah ha! This is cleaner: alphabet = string.ascii_lowercase code = string.ascii_lowercase[2:] + string.ascii_lowercase[:2] Yet it still seems kind of verbose. But since that's the official solution, I guess there's no other way to shift the characters in a string? From wgwigw at gmail.com Thu Mar 30 02:16:49 2006 From: wgwigw at gmail.com (momobear) Date: 29 Mar 2006 23:16:49 -0800 Subject: does python could support sequence of short or int? Message-ID: <1143703009.628171.203020@i39g2000cwa.googlegroups.com> hi, is there a way to let python operate on sequence of int or short? In C, we just need declare a point, then I could get the point value, just like: short* k = buffer, //k is a point to a sequence point of short. short i = *k++, but python is a dynamic language, a = buffer i = ? I don't know how to continue, what's a? a seems to be a str? From fredrik at pythonware.com Thu Mar 16 14:14:01 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Mar 2006 20:14:01 +0100 Subject: Cheese Shop: some history for the new-comers References: <44126523$0$1016$afc38c87@news.optusnet.com.au> <1142529722.091761.316050@p10g2000cwp.googlegroups.com> <1142534429.506300.87620@j33g2000cwa.googlegroups.com> Message-ID: Paul Boddie wrote: > > one of the richest people on earth did define what developers are: > > > > http://www.ntk.net/ballmer/mirrors.html > > I was wondering when someone would mention the "developers, developers, > developers" Ballmer song-and-dance incident: clearly, he isn't chanting > about internal Microsoft project teams. since when is Microsoft a programming language ? From tgrav at mac.com Wed Mar 22 12:13:58 2006 From: tgrav at mac.com (Tommy Grav) Date: Wed, 22 Mar 2006 12:13:58 -0500 Subject: SciPy problem In-Reply-To: <1142964066.915730.297000@i40g2000cwc.googlegroups.com> References: <1142964066.915730.297000@i40g2000cwc.googlegroups.com> Message-ID: <90D115E1-B074-43FF-A994-32117D812699@mac.com> I am new to Python and just downloaded ActivePython 2.4.2.10 on my Mac PPC with OS X 10.4. I added the numpy package (0.9.6-py2.4) and it imports fine. But when I try to import scipy (0.4.8-py2.4) I get an error: >>> import scipy Traceback (most recent call last): File "", line 1, in ? File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/site-packages/scipy/__init__.py", line 32, in ? from numpy import * File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/site-packages/numpy/f2py/__init__.py", line 6, in ? import tempfile File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/tempfile.py", line 33, in ? from random import Random as _Random ImportError: cannot import name Random importing random works fine, so I don't understand what the problem is. Can anyone provide any clues? 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: From cretin at des.alpes.ch Fri Mar 17 11:53:10 2006 From: cretin at des.alpes.ch (Azolex) Date: Fri, 17 Mar 2006 17:53:10 +0100 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> Message-ID: <441ae97e$1_1@news.bluewin.ch> sa wrote: > in k: > > cp:{[c;n;p]+(n#c)_vs(!_ c^n)_dvl,/{2_sv+(,/,/:\:)/(),/:@[x;&x=-1;:[;!c]]}'p} That one goes a long way as a proof of eg evolution theory, you know, monkeys reproducing shakespeare with a typewriter k-board and all that :) > > examples: > > cp[2;3;,0 -1 1] > (0 0 0 > 0 1 0 > 1 0 0 > 1 0 1 > 1 1 0 > 1 1 1) > > cp[2;3;(0 -1 1;1 -1 0)] > (0 0 0 > 0 1 0 > 1 0 1 > 1 1 1) > > cp[2;3;(0 -1 1;1 -1 1)] > (0 0 0 > 0 1 0 > 1 0 0 > 1 1 0) > > arguments of cp: > > c = cardinality of the input set > n = power > p = list of patterns (-1 = wildcard) > > the algorithm directly computes the target set. in other words, > it does not generate the set, then filter the matches from the > target. > > modifying cp to accept s instead of the cardinality of s, > patterns expressed in terms of elements of s, &c. adds nothing > of interest to the problem. From spe.stani.be at gmail.com Sun Mar 12 01:29:39 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 11 Mar 2006 22:29:39 -0800 Subject: Python IDE: great headache.... References: <1142120002.912902.69630@i40g2000cwc.googlegroups.com> Message-ID: <1142144979.714803.190660@u72g2000cwu.googlegroups.com> I've got used to SPE(editor)+WinPdb(debugger) not surprisingly of course ;-) Concerning the free-of-charge IDE's, things might change quite a bit. You might have read this: http://groups.google.nl/group/comp.lang.python.announce/browse_thread/thread/240c000583168029/2dec4ae34efe16e2#2dec4ae34efe16e2 Feel free to wiki on http://pyxides.stani.be Stani -- http://pythonide.stani.be From steve at holdenweb.com Fri Mar 10 03:23:08 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 10 Mar 2006 08:23:08 +0000 Subject: creating variable in root namespace from module In-Reply-To: <1141976796.594066.229210@e56g2000cwe.googlegroups.com> References: <1141976796.594066.229210@e56g2000cwe.googlegroups.com> Message-ID: MakaMaka wrote: > Hi, > I have a scope related question that I haven't been able to find an > answer to anywhere. Is there a way to have a function in an imported > module add variables to the scope of the calling script? Basically, > can I have the following: > > #root.py > import some_module.py > > some_module.afunction() # <== create a variable x1=1 and add it to the > scope of root.py > > print x1 # <== would print 1 > > I know this can be accomplished by passing the what globals() returns > into the function; however, I'm wondering if there is a way to do this > without passing anything to the function. > There are clever technical ways to do this, but what's the use case? There's almost certainly a better way to accomplish what you want. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From mtobis at gmail.com Mon Mar 20 18:48:17 2006 From: mtobis at gmail.com (Michael Tobis) Date: 20 Mar 2006 15:48:17 -0800 Subject: can't rebind magic methods In-Reply-To: <1142887135.270380.123040@g10g2000cwb.googlegroups.com> References: <1142727958.529520.302980@j33g2000cwa.googlegroups.com> <1hceppf.1smucdv4fkudsN%aleaxit@yahoo.com> <1142887135.270380.123040@g10g2000cwb.googlegroups.com> Message-ID: <1142898497.211973.272030@g10g2000cwb.googlegroups.com> Still a bit confused actually. Any explanation of the following? mt #### def getf(method,name): def f(self, *a, **k): return method(self.val, *a, **k) f.func_name = name return f class myint(object): def __init__(self, val): self.val = int(val) for spec in 'str repr hash hex oct pow add'.split(): name = '__%s__' % spec method = getattr(int, name) # comment this out to get the non-working case setattr(myint,name,getf(method,name)) # works # uncomment three lines to get the non-working case # raises TypeError: "expected 1 arguments, got 0" at method invocation # why isn't this equivalent to the setattr above? # def f(self, *a, **k): return method(self.val, *a, **k) # f.func_name = name # setattr(myint,name,f) # doesn't work if __name__ == "__main__": a = myint(42) print a print oct(a) From nick at craig-wood.com Thu Mar 2 13:30:13 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 02 Mar 2006 12:30:13 -0600 Subject: instances from bound methods Message-ID: I needed to find the instance from a bound method. Eg >>> class C(object): ... def fn(self): print "hello" ... >>> c=C() >>> fn=c.fn >>> fn > >>> fn.im_self <__main__.C object at 0xb7dd2acc> >>> fn.__self__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'function' object has no attribute '__self__' >>> But I discovered that builtin objects work in a completely different way >>> fd=open("myfile","w") >>> fn=fd.write >>> fn.im_self Traceback (most recent call last): File "", line 1, in ? AttributeError: 'builtin_function_or_method' object has no attribute 'im_self' >>> fn.__self__ >>> I wonder why? Is there a canonical way of doing it? -- Nick Craig-Wood -- http://www.craig-wood.com/nick From wkehowski at cox.net Fri Mar 17 06:28:49 2006 From: wkehowski at cox.net (wkehowski at cox.net) Date: 17 Mar 2006 03:28:49 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: <1142589945.078364.32870@i39g2000cwa.googlegroups.com> References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1142589945.078364.32870@i39g2000cwa.googlegroups.com> Message-ID: <1142594929.172231.133060@p10g2000cwp.googlegroups.com> You may be interested in, or already know about http://www.lambdassociates.org/ http://www.lambdassociates.org/aboutqi.htm http://www.lambdassociates.org/webbook/contents.htm http://www.lambdassociates.org/prolog.htm Let me know what you think. From larswp at void.dk Thu Mar 23 09:40:19 2006 From: larswp at void.dk (Lars Woetmann) Date: Thu, 23 Mar 2006 15:40:19 +0100 Subject: definition of sub-functions in the hotshot profiler Message-ID: what is the definition of sub-functions in the hotshot profiler? and just as important what is not sub-functions from the output I can see that functions I made and functions in /usr/lib/python2.4/textwrap.py is considered sub-functions, but I call a lot of other functions in the python library and they are not in the output, so how come textwrap is? --code import hotshot, hotshot.stats prof = hotshot.Profile("openAnswerWindow.prof") prof.runcall(self.openAnswerWindow) prof.close() stats = hotshot.stats.load("openAnswerWindow.prof") stats.sort_stats('time', 'calls') stats.print_stats() --output 195 function calls in 0.005 CPU seconds Ordered by: internal time, call count ncalls tottime percall cumtime percall filename:lineno(function) 1 0.001 0.001 0.005 0.005 /home/lars/skole/scriptsprog/rapport/code/m/kw/KeywordWindow.py:399(openAnswerWindow) 18 0.001 0.000 0.002 0.000 m/kw/AnswerWindow.py:22(setText) 9 0.001 0.000 0.001 0.000 include/FancyListViewItem.py:7(__init__) 1 0.000 0.000 0.003 0.003 m/kw/AnswerWindow.py:53(setQuestionItem) 18 0.000 0.000 0.001 0.000 /usr/lib/python2.4/textwrap.py:292(wrap) 18 0.000 0.000 0.000 0.000 /usr/lib/python2.4/textwrap.py:265(wrap) 9 0.000 0.000 0.001 0.000 m/kw/AnswerWindow.py:11(__init__) 18 0.000 0.000 0.000 0.000 /usr/lib/python2.4/textwrap.py:94(__init__) 9 0.000 0.000 0.001 0.000 /home/lars/skole/scriptsprog/rapport/code/include/IntColumnListViewItem.py:7(__init__) 36 0.000 0.000 0.000 0.000 m/kw/AnswerWindow.py:29(text) 1 0.000 0.000 0.000 0.000 /home/lars/skole/scriptsprog/rapport/code/m/kw/QuestionSetModel.py:378(getAllAnswers) 18 0.000 0.000 0.000 0.000 /usr/lib/python2.4/textwrap.py:131(_split) 18 0.000 0.000 0.000 0.000 /usr/lib/python2.4/textwrap.py:114(_munge_whitespace) 18 0.000 0.000 0.000 0.000 /usr/lib/python2.4/textwrap.py:192(_wrap_chunks) 2 0.000 0.000 0.000 0.000 m/kw/AnswerWindow.py:48(setTitle) 1 0.000 0.000 0.000 0.000 m/kw/AnswerWindow.py:71(clearAll) 0 0.000 0.000 profile:0(profiler) From jedp at ilm.com Thu Mar 30 19:46:02 2006 From: jedp at ilm.com (Jed Parsons) Date: Thu, 30 Mar 2006 16:46:02 -0800 Subject: logging producing redundant entries Message-ID: <442C7BCA.901@ilm.com> Hi, I'm using the logging module for the first time. I'm using it from within Zope Extensions. My problem is that, for every event logged, the logger is producing multiple identical entries with the timestamp the same down to the millisecond. Is this something I'm doing wrong? Log snippet: 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons 2006-03-30 16:20:14,173 INFO: Login: Jed Parsons I would like only one of the above lines in my log file; not all those copies. I'm using this simple logging setup at the top of a zope Extension module: import logging # basicConfig for python 2.3 logging.basicConfig() _logger = logging.getLogger("login") _logger.setLevel(logging.DEBUG) _handler = logging.FileHandler(LOG_ROOT, 'login.log')) _formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s") _handler.setFormatter(_formatter) _logger.addHandler(_handler) So these are global to the module. The log lines above were produced by what I expected would be a single call to _logger.info() in a function in the module: _logger.info("Login: %s %s" % (firstname, lastname)) Can anyone explain what I'm doing wrong? Many thanks, j -- Jed Parsons Industrial Light + Magic (415) 746-2974 grep(do{for(ord){(!$_&&print"$s\n")||(($O+=(($_-1)%6+1)and grep(vec($s,$O++,1)=1,1..int(($_-6*6-1)/6))))}},(split(//, "++,++2-27,280,481=1-7.1++2,800+++2,8310/1+4131+1++2,80\0. What!?"))); From gene.tani at gmail.com Wed Mar 29 10:23:37 2006 From: gene.tani at gmail.com (gene tani) Date: 29 Mar 2006 07:23:37 -0800 Subject: Parsing csh scripts with python In-Reply-To: References: Message-ID: <1143645817.722254.215010@i40g2000cwc.googlegroups.com> Dave Benjamin wrote: > On Tue, 28 Mar 2006, David Hirschfield wrote: > > > I need to be able to parse the script, modify some variable settings and > > then write the script back out so that the only changes are the > > variables I've modified (comments, ordering of statements, etc. must > > remain the same). > > > > I looked at shlex, but I don't think it will do what I need. > > What about regular expressions? > probably overkill here, but you might want to look into one of python's templating libs. They make generating lots of "similar except for..." code and markup relatively painless. From kevin.dahlhausen at gmail.com Thu Mar 2 07:06:17 2006 From: kevin.dahlhausen at gmail.com (kpd) Date: 2 Mar 2006 04:06:17 -0800 Subject: Suggestions for documentation generation? In-Reply-To: References: <1141240014.302680.78850@z34g2000cwc.googlegroups.com> Message-ID: <1141301177.328114.69350@i39g2000cwa.googlegroups.com> Thanks - I took at both. Also at 'percepts', which I used a long time ago (had forgotten about it). Percepts has a great little java applet for viewing the class hierarchy. I don't think it works for python, just C++ though. Looks like doxygen will fit the bill. From sjmaster at gmail.com Fri Mar 24 15:06:43 2006 From: sjmaster at gmail.com (Steve M) Date: 24 Mar 2006 12:06:43 -0800 Subject: Python types In-Reply-To: <1143230541.717833.35440@e56g2000cwe.googlegroups.com> References: <1143230541.717833.35440@e56g2000cwe.googlegroups.com> Message-ID: <1143230803.486024.16730@i39g2000cwa.googlegroups.com> I think it means that names, not objects, are weakly typed. So you can have: a = 4 a = 'hello' and there is no problem. The name 'a' doesn't have any type associated with it. This contrasts with strongly typed language like C where you declare the type of the name (variable) and the compiler objects at compile time if you attempt to assign a value of a different type. From Bil.Kleb at NASA.gov Mon Mar 6 05:18:52 2006 From: Bil.Kleb at NASA.gov (Bil Kleb) Date: Mon, 06 Mar 2006 05:18:52 -0500 Subject: Why I chose Python over Ruby In-Reply-To: References: <1141573450.667103.8930@z34g2000cwc.googlegroups.com> Message-ID: Xavier Morel wrote: > >> 2) Ruby does not have true first-class functions living in the same >> namespace as other variables while Python does : >> >> In Ruby you need extra syntax that ruins the "first-class-ness" : >> > The extra syntax is a side-effect of the parensless call of method, it > doesn't mean that methods are not first-class objects. The parensless calls also allow one to write beautiful DSLs with Ruby. -- Bil http://fun3d.larc.nasa.gov From avenpace at gmail.com Fri Mar 17 16:59:47 2006 From: avenpace at gmail.com (avenpace at gmail.com) Date: 17 Mar 2006 13:59:47 -0800 Subject: python cgi permision error Message-ID: <1142632787.589836.169330@u72g2000cwu.googlegroups.com> Hi I have python cgi script, but when I call it I got server internal error. The log in my apache is [Sat Mar 18 04:17:14 2006] [error] [client 127.0.0.1] (13)Permission denied: exec of '/srv/www/cgi-bin/helo.cgi' failed [Sat Mar 18 04:17:14 2006] [error] [client 127.0.0.1] Premature end of script headers: helo.cgi [Sat Mar 18 04:20:09 2006] [notice] caught SIGTERM, shutting down I have set the correct permision for the script(755) and the script is also own by apache uid. I think somehow apache cannot run python to process my python cgi script, but I don't know what I should do anymore. When I run it via shell, the cgi work fine I also can't make my mod_python .py write anything inside my /var/www dir although permision already true, even if I gave /var/www permision recursively to 777(I know this not good idea, just for testing), still have permision denied stuff. Btw I'm using SuSE 10, Apache/2.0.54, and python 2.4 Sighhh, there's a lot of weird thing with my apache and I can't understand why :'( From dananrg at yahoo.com Thu Mar 2 04:54:28 2006 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: 2 Mar 2006 01:54:28 -0800 Subject: PythonWin: any way to delete all objects without exiting and without doing it with "del"? In-Reply-To: <87wtfd7r4c.fsf@voodoo.myself> References: <1141250922.615071.68700@i39g2000cwa.googlegroups.com> <87wtfd7r4c.fsf@voodoo.myself> Message-ID: <1141293267.991614.156170@i39g2000cwa.googlegroups.com> > PythonWin is just an IDE. For what reason you have to delete all objects by > yourself? Garbage collector is there for that :) I think the garbage collector is on strike. :-) Example: # 1st execution a = [1,2,3] print a >>> [1,2.3] program ends. Then I comment out a = [1,2,3] and run the program: # 2nd execution # a = [1,2,3] print a >>> [1,2,3] Same result. Why? I know that's not a great example, but it was giving me grief in the debugging process while using the ODBC module. I'd really rather not have to exit out of PythonWin each time I want to clear out all the objects I created during a script, and then subsequently comment out for future executions of a script for debugging, if that makes any sense. From plahey at alumni.caltech.edu Sat Mar 11 02:00:03 2006 From: plahey at alumni.caltech.edu (plahey at alumni.caltech.edu) Date: 10 Mar 2006 23:00:03 -0800 Subject: API/C memory mananegemnt problem In-Reply-To: <1142056998.489727.168570@e56g2000cwe.googlegroups.com> References: <200603100919.29946.fumana@mi.iasf.cnr.it> <1142056998.489727.168570@e56g2000cwe.googlegroups.com> Message-ID: <1142060403.333298.86840@e56g2000cwe.googlegroups.com> Sorry for responding to my own post. I think I understand the original statement now. What you are really saying is that there is a pool of Python float objects (which can, at different times, wrap different values) which can grow but never decrease in size. So the memory held by this pool is dictated by the maximum number of floats that have ever been simultaneously active (accessible). The same goes for integers. All the more reason to avoid range(.) and use xrange(.). So is this correct? Thanks! From tjreedy at udel.edu Fri Mar 10 18:27:35 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 10 Mar 2006 18:27:35 -0500 Subject: Python and C References: <1142001002.398147.199140@j52g2000cwj.googlegroups.com> <1142028064.100012.256170@v46g2000cwv.googlegroups.com> Message-ID: "P Boy" wrote in message news:1142028064.100012.256170 at v46g2000cwv.googlegroups.com... > I have recently found another approach by using ctypes (http://starship.python.net/crew/theller/ctypes/). Ctypes is now a 2.5 standard lib module and in being tested as such on multiple systems. > I have a library from Microsoft, ewfapi.dll, ewfapi.lib (not required), and ewfapi.h (from msdn.com) Has anyone yet written a program to grab C struct declaration from the .h to produce code like # Overlay configuration class OverlayStoreConfig(ctypes.Structure): _fields_ = [('FormatVersion', ctypes.c_ulong), ('VolumeSize', ctypes.c_longlong), ('NumSegments', ctypes.c_ulong), ('FreeSegments', ctypes.c_ulong), ('SegmentSize', ctypes.c_ulong), ('MaxVolumes', ctypes.c_ulong), ('NumVolumes', ctypes.c_ulong), ('MaxLevels', ctypes.c_ushort), ('VolumeDescArray', pVolumeDesc), ] ? Would save tedium and errors and make ctypes even more helpful. Terry Jan Reedy From dingbat at codesmiths.com Sun Mar 19 18:37:51 2006 From: dingbat at codesmiths.com (Andy Dingley) Date: Sun, 19 Mar 2006 23:37:51 +0000 Subject: Xah's Edu Corner: The Concepts and Confusions of Pre-fix, In-fix, Post-fix and Fully Functional Notations References: <1142490052.127055.50130@v46g2000cwv.googlegroups.com> <1142585935.934786.115700@e56g2000cwe.googlegroups.com> <441a8dd7$0$21666$9b4e6d93@newsread2.arcor-online.net> Message-ID: On Fri, 17 Mar 2006 11:22:06 +0100, Timo Stamm wrote: >Xah's posting was properly encoded and will display fine in every decent >newsreader. Well mine killfiled it straight off, which I think is entirely proper rendering for one of Xah Lee's kookery lessons. From reply.in.the.newsgroup at my.address.is.invalid Thu Mar 23 05:58:04 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 23 Mar 2006 11:58:04 +0100 Subject: Good thread pool module References: <1143092128.647987.58120@u72g2000cwu.googlegroups.com> Message-ID: Dennis Lee Bieber: >Raymond Hettinger: >> Because of the GIL, thread pools are not as useful in Python as you >> might expect -- they execute one at a time and do not take advantage of >> hyper-threading or multiple processors. If that kind of efficiency is > > If the task is I/O bound (something like a web spider?), seems >they'd still be useful... Yes, I use a thread pool for that. But async I/O may be a more efficient solution (e.g. Twisted). -- Ren? Pijlman Wat wil jij leren? http://www.leren.nl From mbukhin at gmail.com Wed Mar 29 03:06:22 2006 From: mbukhin at gmail.com (mbukhin at gmail.com) Date: 29 Mar 2006 00:06:22 -0800 Subject: FTP not Returning (Python on Series 60 Nokia) In-Reply-To: References: <1143618018.661424.234510@v46g2000cwv.googlegroups.com> Message-ID: <1143619582.891407.119360@g10g2000cwb.googlegroups.com> Thanks for the 'debug mode' tip. My file is only 24k (a photo) and the whole thing makes it to the FTP server. It's just the command never returns so my program cannot continue execution. When I do turn debugging on, the last command I see is: *resp* '150 Connection accepted' Could it be my FTP server? I'm using a windows install of FileZilla. I did have to make one patch to the ftplib. There is a documented problem where routers mangle return text: 227 Entering Passive Mode (192,168,0,3,13,248) into something like 227 Entring Passive Mode (192,168,0,3,13,248 Pulling off the trailing paren (see: http://filezilla.sourceforge.net/forum/viewtopic.php?p=6109&sid=d9126f7830afe301c7e4948c2c84153b). I edited the parse227 call to not look for the trailing paren. Anywhere else i can look? I'm running my program line by line in the bluetooth console and it hangs on the storbinary. When I run the program directly on the phone as a single exe the same thing happens. thanks (Code & output) Sample Code: from appuifw import * from graphics import * from ftplib import FTP import camera import e32 import time import httplib, urllib from key_codes import * picselection = 'e:\\picture.jpg' ftp = FTP('xx.xx.xxx.xxx') # connect to host ftp.set_debuglevel(2) ftp.set_pasv('true') ftp.login('mike','xxxxx') F=open(picselection,'rb') filename = time.strftime("%Y-%m-%d-%H-%M-%S.jpg",time.localtime()) e32.ao_yield() ftp.storbinary('STOR ' + filename,F,1024) # store the image e32.ao_yield() ftp.quit() F.close() Debug output: *cmd* 'USER mike'*put* 'USER mike\r\n' *get* '331 Password required for mike\r\n' *resp* '331 Password required for mike' *cmd* 'PASS *******' *put* 'PASS *******\r\n' *get* '230 Logged on\r\n' *resp* '230 Logged on''230 Logged on' >>> F=open(picselection,'rb') >>> filename = time.strftime("%Y-%m-%d-%H-%M-%S.jpg",time.localtime()) >>> e32.ao_yield() >>> ftp.storbinary('STOR ' + filename,F,1024) # store the image *cmd* 'TYPE I' *put* 'TYPE I\r\n' *get* '200 Type set to I\r\n' *resp* '200 Type set to I' *cmd* 'PASV' *put* 'PASV\r\n' *get* '227 Entring Passive Mode (69,86,224,242,13,248\r\n' *resp* '227 Entring Passive Mode (69,86,224,242,13,248' *cmd* 'STOR 2006-03-29-02-59-13.jpg' *put* 'STOR 2006-03-29-02-59-13.jpg\r\n' *get* '150 Connection accepted\r\n' *resp* '150 Connection accepted' From fabiofz at gmail.com Wed Mar 29 16:26:31 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 29 Mar 2006 18:26:31 -0300 Subject: Free Python IDE ? In-Reply-To: References: <1143653654.234759.133800@j33g2000cwa.googlegroups.com> Message-ID: On 3/29/06, Jarek Zgoda wrote: > > Ernesto napisa?(a): > > > I'm looking for a tool that I can use to "step through" python software > > (debugging environment). Is there a good FREE one (or one which is > > excellent and moderately priced ) ? > > Good free: PyDev for Eclipse. > Good moderately priced: Komodo. You forgot excellent and moderately priced: Pydev Extensions ;-P (it is an extension to Pydev that adds many nice features... check it at http://www.fabioz.com/pydev). Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From blacklist-me at davjam.org Mon Mar 13 23:42:30 2006 From: blacklist-me at davjam.org (David Bolt) Date: Tue, 14 Mar 2006 04:42:30 +0000 Subject: sizeof(struct timeval) References: Message-ID: <1p0$4Eb2mkFEFwH6@dev.null.davjam.org> On Tue, 14 Mar 2006, Tony Houghton wrote:- >In any case, it does imply that timeval can be relied on to be 2 * >32-bits (2 * long) in 32-bit architectures and something else in 64-bit >architectures - where long is 64-bit. Using the source below for a quick test on both a 32 and 64 bit SUSE system[0], I get a size of 8 bytes on the 32 bit system, which implies 2 * 32 bit, and 16 ( 2 * 64 bit) on the 64 bit system. /* quick, boring, and probably could do with a major cleanup but it should be fine */ #include #include #include #include int main(void) { int the_size=sizeof(struct timeval); printf("%u\n", the_size); exit(0); } [0] see .sig for details. Regards, David Bolt -- Member of Team Acorn checking nodes at 50 Mnodes/s: http://www.distributed.net/ AMD1800 1Gb WinXP/SUSE 9.3 | AMD2400 256Mb SuSE 9.0 | A3010 4Mb RISCOS 3.11 AMD2400(32) 768Mb SUSE 10.0 | RPC600 129Mb RISCOS 3.6 | Falcon 14Mb TOS 4.02 AMD2600(64) 512Mb SUSE 10.0 | A4000 4Mb RISCOS 3.11 | STE 4Mb TOS 1.62 From vbgunz at gmail.com Sun Mar 5 07:45:05 2006 From: vbgunz at gmail.com (vbgunz) Date: 5 Mar 2006 04:45:05 -0800 Subject: Argument Precedence (possible bug?) In-Reply-To: <1141562380.331820.42260@i40g2000cwc.googlegroups.com> References: <1141562380.331820.42260@i40g2000cwc.googlegroups.com> Message-ID: <1141562704.979483.63730@i40g2000cwc.googlegroups.com> Hello all, I am just learning Python and have come across something I feel might be a bug. Please enlightenment me... The following code presents a challenge. How in the world do you provide an argument for *arg4? ## ============================================================ def argPrecedence(par1, par2=0, par3=0, *par4, **par5): print 'par1 =', par1, ' # positional argument' print 'par2 =', par2, ' # keyword argument' print 'par3 =', par3, ' # keyword argument' print 'par4 =', par4, ' # argument converted to tuple' print 'par5 =', par5, ' # argument converted to dictionary' argPrecedence('arg1', par3='arg3', par2='arg2', arg5='arg5') # argPrecedence Results: par1 = arg1 # positional argument par2 = arg2 # keyword argument par3 = arg3 # keyword argument par4 = () # argument converted to tuple par5 = {'arg5': 'arg5'} # argument converted to dictionary ## ============================================================ The code above is verbose with comments because I am just learning Python and am creating my own examples and reference materials... Can you solve the problem? If so, can you share the solution? If not, is this a bug, limitation or is it a feature? Thank you for your time on this one! PS. I could be far off with this codes purpose; to try and create an example that will house all the different possible parameters (positional, keyword, * and **) in one single def statement. -- Best Regards Victor B. Gonzalez From webcom.dk at gmail.com Thu Mar 16 05:01:39 2006 From: webcom.dk at gmail.com (Jacob) Date: 16 Mar 2006 02:01:39 -0800 Subject: Install Universal Encoding Detector In-Reply-To: References: <1142430310.530681.321760@i39g2000cwa.googlegroups.com> Message-ID: <1142503299.223649.76260@j52g2000cwj.googlegroups.com> How do I uninstall? /Jacob From jordan.taylor2 at gmail.com Fri Mar 3 23:43:20 2006 From: jordan.taylor2 at gmail.com (jordan.taylor2 at gmail.com) Date: 3 Mar 2006 20:43:20 -0800 Subject: socket freezes In-Reply-To: <46rm84Fcet0eU1@individual.net> References: <46qtqqFcej8bU1@individual.net> <46rm84Fcet0eU1@individual.net> Message-ID: <1141447399.964278.254370@i39g2000cwa.googlegroups.com> Might want to check out the SO_REUSEADDR bit in sockets. I believe it helps with a problem of a program not notifying the OS that it's done with the port. Piece of a script (duh): host = "" port = 51423 #random for this example s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) Good Luck :D From abhinavduggal at gmail.com Sun Mar 26 15:23:23 2006 From: abhinavduggal at gmail.com (abhinav) Date: 26 Mar 2006 12:23:23 -0800 Subject: Python multithreading problem Message-ID: <1143404603.763070.319690@z34g2000cwc.googlegroups.com> //A CRAWLER IMPLEMENTATION please run this prog. on the shell and under the control of debugger when this prog. is run normally the prog. does not terminate .It doesn't come out of the cond. if c<5: so this prog. continues infinitely but if this prog is run under the control of debugger the prog terminates when the cond. if c<5: becomes false i think this prob. may be due to multithreading pls help. from sgmllib import SGMLParser import threading import re import urllib import pdb import time class urlist(SGMLParser): def reset(self): SGMLParser.reset(self) self.list=[] def start_a(self,attr): href=[v for k,v in attr if k=="href"] if href: self.list.extend(href) mid=2 c=0 class mythread(threading.Thread): stdmutex=threading.Lock() global threads threads=[] def __init__(self,u,myid): self.u=u self.myid=myid threading.Thread.__init__(self) def run(self): global c global mid if c<5: self.stdmutex.acquire() self.usock=urllib.urlopen(self.u) self.p=urlist() self.s=self.usock.read() self.p.feed(self.s) self.usock.close() self.p.close() c=c+1 fname="/root/" + str(c) + ".txt" self.f=open(fname,"w") self.f.write(self.s) self.f.close() print c print self.p.list print self.u print self.myid for j in self.p.list: k=re.search("^https?:",j) if k: i=mythread(j,mid) i.start() threads.append(i) mid=mid+1 self.stdmutex.release() if __name__=="__main__": thread=mythread("http://www.google.co.in/",1) thread.start() threads.append(thread) for thread in threads: thread.join() print "main thread exits" From wrongbad at gmail.com Fri Mar 31 23:33:57 2006 From: wrongbad at gmail.com (I V) Date: 31 Mar 2006 20:33:57 -0800 Subject: recursion and linked lists In-Reply-To: <442dfe2f$0$2431$c3e8da3@news.astraweb.com> References: <442dfe2f$0$2431$c3e8da3@news.astraweb.com> Message-ID: <1143866037.105827.289850@i39g2000cwa.googlegroups.com> John Salerno wrote: > The printable value of node1 is 1, node2 is 2 and node 3 is 3. > > node1.next is node2, node2.next is node3 and node3.next is None. > > This might be painfully obvious, but I don't understand when the print > statement is getting called. If you call printBackward with node1, then > you skip the if statement, head becomes node1, tail becomes node2 and > then you call printBackward again with node2. During this call you call > printBackward again with node 3 and then the next time the if statement > returns. So when does the print happen, and how does it print 3 > different values? It seems like you wouldn't get to it until the last > time printBackward returns, and 'head' at that point would be 3, which Each time printBackward gets called, it has it's own separate 'head' variable. We could imagine they're all separate variables head1 for the first time printBackward is called, head2 for the second, and so on. The first time printBackwards gets called, it's local 'head' variable (head1) gets set to 1, and so on. > is the first number printed. But doesn't it stop at this point? Where do > 2 and 1 come from? Note that print gets called after _each_ time that printBackward returns. So, as the different calls to printBackward return, they print whatever 'head' was set to in that invocation. Now, logically enough, the last call to printBackward is the first to return, so the last value of 'head' is printed first, and so in in the reverse order of the list. Maybe this will help you visualize what is going on: call printBackward with arg [1, 2, 3] head1 = 1 call printBackward with arg [2, 3] head2 = 2 call printBackward with arg [3] head3 = 3 call printBackward with arg None return print head3 ( == 3) return print head2 (== 2) return print head1 (== 1) return From dbasch at yahoo.com Wed Mar 1 15:07:33 2006 From: dbasch at yahoo.com (Derek Basch) Date: 1 Mar 2006 12:07:33 -0800 Subject: Matplotlib logarithmic scatter plot In-Reply-To: <87d5h6c4wx.fsf@peds-pc311.bsd.uchicago.edu> References: <1141073994.346490.16070@j33g2000cwa.googlegroups.com> <1141075713.027689.66800@t39g2000cwt.googlegroups.com> <1141077576.303733.31070@i40g2000cwc.googlegroups.com> <87irr0o01x.fsf@peds-pc311.bsd.uchicago.edu> <1141085671.456746.175090@i39g2000cwa.googlegroups.com> <87lkvvfjug.fsf@peds-pc311.bsd.uchicago.edu> <1141162577.569974.213920@p10g2000cwp.googlegroups.com> <87d5h6c4wx.fsf@peds-pc311.bsd.uchicago.edu> Message-ID: <1141243653.850251.138510@i40g2000cwc.googlegroups.com> Good tip John. Hopefully it will help someone out. Thanks again. Derek Basch From aleaxit at yahoo.com Sun Mar 19 23:26:46 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 19 Mar 2006 20:26:46 -0800 Subject: Is there such an idiom? References: <1142813592.486643.111550@j33g2000cwa.googlegroups.com> <1142817682.712758.40520@i40g2000cwc.googlegroups.com> Message-ID: <1hcgrew.458e75fxqjewN%aleaxit@yahoo.com> Ron Adam wrote: ... > From what I recently read here (not sure where) in another thread, in > python 2.3 sets were implemented as a python module using dictionaries, > and in 2.4 it was written in C code based on the dictionary C code. ...and in 2.5 they're due to be further optimized, using their own specialized code rather than piggybacking on dictionaries'. Alex From duncan.booth at invalid.invalid Thu Mar 9 14:16:49 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Mar 2006 19:16:49 GMT Subject: timeit.py examples in docs generate error References: Message-ID: 3c273 wrote: > I was reading the thread on try/except overhead and decided to try > Alex's examples but they kept generating exceptions. So I went to the > docs and tried the examples there (copied and pasted) with the same > results (Win2k, Python 2.4). Any help is appreciated. The output > follows: #1 > C:\Python24\Lib>timeit.py 'if hasattr(int, "__nonzero__"): pass' > Traceback (most recent call last): > File "C:\Python24\Lib\timeit.py", line 285, in ? > sys.exit(main()) > File "C:\Python24\Lib\timeit.py", line 249, in main > t = Timer(stmt, setup, timer) > File "C:\Python24\Lib\timeit.py", line 116, in __init__ > code = compile(src, dummy_src_name, "exec") > File "", line 6 > 'if > ^ > SyntaxError: EOL while scanning single-quoted string Window's command processor doesn't recognise single quote marks as meaning anything special, so your command is passing 4 separate arguments to timeit.py instead of the 1 argument that a unix shell would be passing. Try using double quotes around everything instead: timeit.py "if hasattr(int, '__nonzero__'): pass" From greg at cosc.canterbury.ac.nz Tue Mar 7 02:05:11 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 07 Mar 2006 20:05:11 +1300 Subject: ANN: PyGUI 1.6.1 Message-ID: PyGUI 1.6.1 is now available: http://www.cosc.canterbury.ac.nz/~greg/python_gui/ Bug fixes: - Mouse down event in a GLView caused a crash. - Canvas methods fill_poly() and stroke_poly() didn't work. Added a test for these. 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 felipe.lessa at gmail.com Thu Mar 16 10:52:47 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Thu, 16 Mar 2006 12:52:47 -0300 Subject: Computing correlations with SciPy In-Reply-To: <1142524171.358429.129850@i39g2000cwa.googlegroups.com> References: <1142524171.358429.129850@i39g2000cwa.googlegroups.com> Message-ID: <1142524367.6960.1.camel@kenshin> Em Qui, 2006-03-16 ?s 07:49 -0800, tkpmep at hotmail.com escreveu: > I want to compute the correlation between two sequences X and Y, and > tried using SciPy to do so without success.l Here's what I have, how > can I correct it? $ python2.4 Python 2.4.2 (#2, Nov 20 2005, 17:04:48) [GCC 4.0.3 20051111 (prerelease) (Debian 4.0.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x = [1,2,3,4,5] >>> y = [5,4,3,2,1] >>> import scipy >>> scipy.corrcoef(x, y) array([[ 1., -1.], [-1., 1.]]) >>> # Looks fine for me... From maxm at mxm.dk Mon Mar 13 04:45:31 2006 From: maxm at mxm.dk (Max M) Date: Mon, 13 Mar 2006 10:45:31 +0100 Subject: Cheese Shop: some history for the new-comers In-Reply-To: References: <44126523$0$1016$afc38c87@news.optusnet.com.au> Message-ID: <44153edd$0$38704$edfadb0f@dread12.news.tele.dk> A.M. Kuchling wrote: > On Sat, 11 Mar 2006 16:50:26 +1100, > richard wrote: > >>So I did what people always do in this situation, I asked Barry Warsaw to >>name. it. And he did, "Cheese Shop". I liked the name, so it was done. When >>the new pydotorg machines went live last year, so too did the name >>cheeseshop.python.org > > > Given the endless whiny complaints about the name, though, I think we > should just give up and go back to PyPI (pronounced 'Pippy'). When short obscure names are bad in programming, whay are they good in general communication. "Python Packages" is too obvious perhaps? When we start using eggs will it then be renamed to "Dairy Shop" or perhaps "Daisy" to make it obscure? Or the "Chickens Nest"? Please. If it is meant to be used and understood, both Cheeseshop and Pypi are bad names. -- 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 hancock at anansispaceworks.com Thu Mar 30 16:35:18 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 30 Mar 2006 15:35:18 -0600 Subject: a hobbyist's dilemma Message-ID: <442C4F16.6060108@anansispaceworks.com> You may find the attached files of interest. I wrote this PyGame script in order to teach my sons (ages 8 & 10) about some programming concepts. I intentionally avoided any function or class definitions, and tried to use minimal Python concepts. I think it's quite impressive that you can do a demo this simple in PyGame. None of the examples distributed with PyGame are quite this simple (they probably represent better program design, but this is all about KISS). It uses the PyGame logo (you can download that separately -- it's part of the documentation for PyGame. You could replace it with any image you want, of course), and makes it do a "drunkard's walk" around the screen. Successive versions of the script show different kinds of behaviors, from bouncing off of the walls, to responding to key presses. Armed with this, a decent Python book, and the PyGame API documentation (which is excellent, BTW), you should be able to get on your way quickly. I originally called it "drunk.py", but I figured "wiggle.py" was more PC. ;-) I chose PyGame for this, because: 1) Like me, my kids are very motivated by "pretty pictures" -- much more so than by "guess the number" text games. I learned how to program using BASIC on a TRS-80 Color Computer, and just about all I did for the first couple of years was program screen graphics. 2) It's easier to "hack" a working program than to write from scratch 3) PyGame is something they actually want to learn how to use, because I can point to real games written using it which I know they like to play (e.g. "SolarWolf"). 4) Motivation is more important than ease or skill! I think you can see that PyGame isn't much harder than writing a line-based terminal program, as long as you don't expect too much (line-based programs can be hard too, if they're complicated, of course). Phil: I'm CC'ing you, because you may consider this contributed to PyGame's website if you want to use it -- in fact, you can do anything you want with it, "I consign it to the Public Domain." Cheers, Terry -------------- next part -------------- A non-text attachment was scrubbed... Name: wiggle.tgz Type: application/x-gtar Size: 1144 bytes Desc: not available URL: From bearophileHUGS at lycos.com Tue Mar 7 17:39:55 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 7 Mar 2006 14:39:55 -0800 Subject: Type Hinting vs Type Checking and Preconditions References: Message-ID: <1141771195.388194.248780@e56g2000cwe.googlegroups.com> Delaney, Timothy (Tim): > Search for `python optional static typing` for discussions - the first > two links from Google are blog entries by Guido from a year ago (there's > also a third one linked from PEP 3000). I am sorry. Yes, I have read those posts about a year ago, and I remember most of them, but I can remember that the syntax was discussed a lot... Nothing real has come out of those discussions, I think. We'll see. I like the typecheck API, it's not perfect but it's not bad (and can probably be improved still, removing some parts, changing some names, adding some things, etc.) and it allows most of the things suggested by Guido, plus other things, without the need to change the language syntax at all. Can't such annotations be used by the interpreter (and by Psyco) to produce much faster code? I remember that for Guido the purpose of optional types wasn't much for speed, but for other purposes (like to build very large and complex systems, as Zope), but using it for speed purposes in smaller programs too can be cute :-) Bye, bearophile From fredrik at pythonware.com Tue Mar 21 14:33:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 21 Mar 2006 20:33:47 +0100 Subject: Why "class exceptions" are not deprecated? References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com> Message-ID: Gregory Petrosyan wrote: > 1) From 2.4.2 documentation: > There are two new valid (semantic) forms for the raise statement: > raise Class, instance > raise instance > > 2) In python: > >>> raise NameError > Traceback (most recent call last): > File "", line 1, in ? > NameError > >>> help(NameError) > Help on class NameError in module exceptions: ... > >>> raise 0 > Traceback (most recent call last): > File "", line 1, in ? > TypeError: exceptions must be classes, instances, or strings > (deprecated), not i > nt > > So, if it's a bug in documentation, it should be corrected. Otherwise, > (IMHO!) raising classes should be deprecated. it could be that the tutorial author expected you to read chapter 8 before you read chapter 9, and used "new" to mean forms that hadn't already been described: http://docs.python.org/tut/node10.html > Does raising class make sence? As for me, I can't find any usefull > case for it. as explained in the language reference, raise Class is the same thing as raise Class() From paul at boddie.org.uk Fri Mar 10 10:49:37 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 10 Mar 2006 07:49:37 -0800 Subject: Python Evangelism In-Reply-To: References: Message-ID: <1142005777.058808.198630@e56g2000cwe.googlegroups.com> John Pote wrote: > > Over this side of the pond the good old British Post Office changed its name > to 'Consignia' in 2001. I thought it was actually the Royal Mail, but the brand history can be found here: http://www.royalmailgroup.com/aboutus/aboutus8.asp The fact that people confuse "Royal Mail" with "Post Office" might suggest something to brand experts, but I'd argue that pulling one of the names out of use, especially the one people tend not to use (but the one they've now chosen for the parent company), would suggest something else to normal people: it would either weaken the dual-named "superbrand" or merely be regarded with contempt. Examples can be found for this and other re-branding cases quite readily on the Internet, but don't search for 'Consignia "Royal Mail"' in Google, though, as it seems to result in a bizarre error page: """ We're sorry... ... but your query looks similar to automated requests from a computer virus or spyware application. To protect our users, we can't process your request right now. """ Anyway, aside from bizarre technical moments like this, what you've described can probably be termed "brand suicide": the scrapping of a recognisable brand identity with something fashionable at a particular point in time that looks dated within a few years, and which has people wondering who they're doing business with (despite extensive publicity), only to discover that it's been the same company all along. [...] > what's in a name? fortran, algol, rexx, hope, haskell, pascal, modula, > eiffel, B, C, J, tcl, pearl, ruby, rebol, cobol, basic, vb, .net, assembler, > forth, snobol, ada, prolog, simula, smalltalk, oberon, dylan, bob, ML et al > ad nauseum. > - is Python any less meaningful? Anyway I LIKE the chesse shop sketch! The problem with the Cheese Shop name, aside from sounding ridiculous, is that it isn't self-explanatory in an area which needs self-explanatory labelling. Consider the following conversations: A: "I need to find something in Python that does this." B: "Have you tried the Python Package Index?" A: "Don't know why I didn't think of that!" A: "I need to find something in Python that does this." B: "Have you tried the Cheese Shop?" A: "WTF is that?" [Lengthy, embarrassed explanation follows.] Bizarre names may be cute (to some people) but they don't lend themselves to guessing or searching. Consequently, people who want answers yesterday aren't likely to be amused to eventually discover that the name of the resource they've been looking for is some opaque, three-levels-of-indirection-via-irony, in-crowd joke. And even acronyms like CPAN are better than wacky names, anyway. Paul From cito at online.de Wed Mar 1 17:28:24 2006 From: cito at online.de (Christoph Zwerschke) Date: Wed, 01 Mar 2006 23:28:24 +0100 Subject: Proper class initialization In-Reply-To: References: Message-ID: Jack Diederich wrote: > ... __metaclass__ = MyMeta Thanks. I was not aware of the __metaclass__ attribute. Still a bit complicated and as you said, difficult to read, as the other workarounds already proposed. Anyway, this is probably not needed so often. -- Christoph From dbasch at yahoo.com Thu Mar 23 14:47:55 2006 From: dbasch at yahoo.com (Derek Basch) Date: 23 Mar 2006 11:47:55 -0800 Subject: Remove integer from float number In-Reply-To: <4422FAA9.50506@websafe.com> References: <1143142664.507941.130240@g10g2000cwb.googlegroups.com> <4422FAA9.50506@websafe.com> Message-ID: <1143143275.684150.299200@i39g2000cwa.googlegroups.com> Ahh yes you have to put parenthases around the string formatting to remove the integer using indexes. Thanks, that's just what I needed! Derek Basch From fredrik at pythonware.com Thu Mar 16 05:47:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Mar 2006 11:47:17 +0100 Subject: recycling internationalized garbage References: <1141827739.823228.198160@j33g2000cwa.googlegroups.com><1142349486.353020.194600@i39g2000cwa.googlegroups.com><1142357837.655528.155460@j33g2000cwa.googlegroups.com><441736A1.3090204@v.loewis.de><1142409981.565148.314030@j52g2000cwj.googlegroups.com> <44191735.5080901@v.loewis.de> Message-ID: "Martin v. L?wis" wrote: >> It should be obvious that any 8-bit single-byte character set can >> produce byte sequences that are valid in UTF-8. > > It is certainly possible to interpret UTF-8 data as if they were > in a specific single-byte encoding. However, the text you then > obtain is not meaningful in any language of the world. Except those languages that uses words consisting of runs of accented letters immediately followed by either undefined characters or odd sym- bols, and never use accented characters in any other way. (Given that the freedb spec says that it's okay to mix iso-8859-1 with utf-8 on a record-by-record level, one might assume that they've de- cided that the number of bands using such languages is very close to zero...) From cesare__m at hotmail.com Fri Mar 31 07:42:38 2006 From: cesare__m at hotmail.com (cesare) Date: Fri, 31 Mar 2006 14:42:38 +0200 Subject: invalid syntax - problems with CR (0x0a) Message-ID: <1143808767_1273@sp6iad.superfeed.net> hi, i'm very new to python and am experiencing the following problem: an identical program that runs on certain computers crashes on other machines due to Carriage Returns (CR; 0x0a) that now appear in the source code. I guess it's some kind of character encoding issue, i.e. ways of saving the source files... I spent a lot of time trying to fix the problem but wasn't successful until now. Can somebody help me? Cheers, Cesare error message inside the log file: Traceback (most recent call last): File "S:\P037_Gewerbeverband\Programm\Testumgebung\meta_search_download_scheduler.py", line 132, in instanceMP exec 'import %s' % mp File "", line 1, in ? File "S:\P037_Gewerbeverband\Programm\Testumgebung\weisseseiten.py", line 87 s = s.replace('.-', ' CHF') s = s.replace(';', ' ') ^ SyntaxError: invalid syntax ----== 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 kent at kentsjohnson.com Wed Mar 22 09:36:41 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 22 Mar 2006 09:36:41 -0500 Subject: struct size confusion: In-Reply-To: References: Message-ID: <44215be7$1_2@newspeer2.tds.net> Michael Yanowitz wrote: > Hello: > > I am relatively new to Python and this is my first post on > this mailing list. > > I am confused as to why I am getting size differences in the following > cases: > > >>>>print struct.calcsize("I") > > 4 > >>>>print struct.calcsize("H") > > 2 > >>>>print struct.calcsize("HI") > > 8 > >>>>print struct.calcsize("IH") > > 6 > > Why is it 8 bytes in the third case and why would it be only 6 bytes > in the last case if it is 8 in the previous? By default the struct module uses native byte-order and alignment which may insert padding. In your case, the integer is forced to start on a 4-byte boundary so two pad bytes must be inserted between the short and the int. When the int is first no padding is needed - the short starts on a 2-byte boundary. To eliminate the padding you should use any of the options that specify 'standard' alignment instead of native: In [2]: struct.calcsize('I') Out[2]: 4 In [3]: struct.calcsize('H') Out[3]: 2 In [4]: struct.calcsize('HI') Out[4]: 8 In [5]: struct.calcsize('IH') Out[5]: 6 In [6]: struct.calcsize('!HI') Out[6]: 6 In [7]: struct.calcsize('>HI') Out[7]: 6 In [8]: struct.calcsize(' > I tried specifying big endian and little endian and they both have > the same results. Are you sure? They should use standard alignment as in the example above. > > I suspect, there is some kind of padding involved, but it does not > seem to be done consistently or in a recognizable method. > > I will be reading shorts and longs sent from C into Python > through a socket. > > Suppose I know I am getting 34 bytes, and the last 6 bytes are a 2-byte > word followed by a 4-byte int, how can I be assured that it will be in that > format? > > In a test, I am sending data in this format: > PACK_FORMAT = "HBBBBHBBBBBBBBBBBBBBBBBBBBHI" > which is 34 bytes Are you sure? Not for me: In [9]: struct.calcsize('HBBBBHBBBBBBBBBBBBBBBBBBBBHI') Out[9]: 36 Kent From tim at pollenation.net Tue Mar 21 07:00:56 2006 From: tim at pollenation.net (Tim Parkin) Date: Tue, 21 Mar 2006 12:00:56 +0000 Subject: New-style Python icons In-Reply-To: <1142941650.645803.317470@t31g2000cwb.googlegroups.com> References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> <1142941650.645803.317470@t31g2000cwb.googlegroups.com> Message-ID: <441FEAF8.1040004@pollenation.net> Luis M. Gonz?lez wrote: >This is strange... I've been trying to access this site since >yesterday, but I couldn't (Firefox can't stabilish connection with >server www.doxdesk.com). >However, I seem to be the only one with this problem... > > > You could try using a proxy (one of the anonymous proxies would do the job). Tim Parkin From xavier.morel at masklinn.net Mon Mar 6 11:31:13 2006 From: xavier.morel at masklinn.net (Xavier Morel) Date: Mon, 06 Mar 2006 17:31:13 +0100 Subject: how do you move to a new line in your text editor? In-Reply-To: <%ZGNf.1711$No6.40016@news.tufts.edu> References: <%ZGNf.1711$No6.40016@news.tufts.edu> Message-ID: John Salerno wrote: > So I'm wondering, how do you all handle moving around in your code in > cases like this? Is there some sort of consistency to these things that > you can write rules for your text editor to know when to outdent? It > doesn't seem like you can do this reliably, though. Under windows, I'm using SciTE which is an extremely lightweight editor, but it handlers "smart unindent": pressing backspace at the beginning of a line unindents one level, whether you're indenting with tabs (and need to remove a tab) or space (and need to remove 2, 4, 8 spaces) doesn't matter. And since SciTE also has Visual Studio's smart home key (home brings you first at the beginning of the text == current indent, then at the beginning of the line itself == indent level 0) SciTE also features "somewhat smart" indent from time to time: it indents one level after a ":". This is good for if/else/while/..., but it also indents one level after ":" in dicts, which is way bad. Oh, and it automatically unindents one level after a "return" statement. Other than that, SciTE doesn't really "understand" python, if you want a really pythonic editor you need to check Stani's Python Editor, WingsIDE or Komodo. From mensanator at aol.com Fri Mar 24 16:53:40 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 24 Mar 2006 13:53:40 -0800 Subject: a problem to solve References: <5oiUf.1818$No6.41433@news.tufts.edu> Message-ID: <1143237220.103038.52200@t31g2000cwb.googlegroups.com> John Salerno wrote: > John Salerno wrote: > > > Anyway, any advice for how to proceed would be great! I hope I described > > it well enough. > > Ok, after reading the suggestions, I feel better about proceeding. But > one question: how exactly do I come up with 32 different 20-bit integers > for each switch? Eight numbers for each switch, 32 total. Make a list for each panel and in each list, put in eight binary numbers using the position in the list to represent the switch number. So we'll want to label our switches 0-7. > Do I need to figure out the bits for each one manually? Yes, you get them from your diagram showing which lamps are lit for each switch. > And how is this written in Python? Using hex? That's one way to do it. I did it that way because I have the hex patterns memorized. I have already gone to the trouble of converting all your patterns to hex numbers, if you're interested. If you want to do it yourself, simply ignore this. a = [0xf5fdc,0xf6edb,0xbddb7,0x6fddd,0xeb7ed,0xb977f,0xbfed3,0xedef5] b = [0xddb7d,0xfaddb,0xde75f,0xeef7a,0xdd77b,0xdfbce,0xb77dd,0x7ef5d] c = [0xf37bd,0xdfaee,0xddd6f,0xddfb6,0xb9efb,0xb7bbe,0xecfbd,0xb75df] d = [0x77edb,0xbb7ee,0xdf773,0x7bdeb,0x7ddaf,0xdeeeb,0xfb35f,0xbb7dd] Now since the panels are now lists, we use an index representing the switch to retrieve the lamps lit by that switch. Refering to my original boolean equation, replace A1 by a[0], B1 by b[0], etc. to evaluate that set of switches. Once you see that a[0],b[0],c[0],d[0] is not a solution, try a different set of switches. Repeat until you find a set that works. There is, in fact a solution, but I won't reveal it unless you ask. If you need help in figuring out how to walk through all 4096 possible switch sets, just ask. From http Sat Mar 4 16:33:26 2006 From: http (Paul Rubin) Date: 04 Mar 2006 13:33:26 -0800 Subject: The old round off problem? References: <1141498826.719803.114490@u72g2000cwu.googlegroups.com> Message-ID: <7xslpxki8p.fsf@ruckus.brouhaha.com> "sam" writes: > Hello all, I am taking a class in scientific programming at the local > college. My problem is that the following difference produces round off > errors as the value of x increases. For x >= 19 the diference goes to > zero.I understand the problem, but am curious as to whether their > exists a solution. [f(x) = cosh^2(x) - sinh^2(x) = 1] The usual way is to notice that the difference goes to zero because the lowest order terms of the Taylor series for cosh^2 and sinh^2 are equal and cancel each other out. The solution is to write down the series for (cosh^2(x) - sinh^2(x)) and add up a few non-cancelled terms. All these series should converge very fast. From bj_666 at gmx.net Wed Mar 8 17:24:31 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 08 Mar 2006 23:24:31 +0100 Subject: %r References: <75-dnc5y7fLN-ZHZRVnzvA@telenor.com> Message-ID: In , Blackbird wrote: > By "cargo cult programming", do you mean actually *running* the code? http://www.catb.org/~esr/jargon/html/C/cargo-cult-programming.html Ciao, Marc 'BlackJack' Rintsch From johnjsal at NOSPAMgmail.com Fri Mar 31 23:13:28 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 31 Mar 2006 23:13:28 -0500 Subject: recursion and linked lists Message-ID: <442dfe2f$0$2431$c3e8da3@news.astraweb.com> Can someone explain to me how this works: def printBackward(list): if list == None: return head = list tail = list.next printBackward(tail) print head, >>> printBackward(node1) 3 2 1 The printable value of node1 is 1, node2 is 2 and node 3 is 3. node1.next is node2, node2.next is node3 and node3.next is None. This might be painfully obvious, but I don't understand when the print statement is getting called. If you call printBackward with node1, then you skip the if statement, head becomes node1, tail becomes node2 and then you call printBackward again with node2. During this call you call printBackward again with node 3 and then the next time the if statement returns. So when does the print happen, and how does it print 3 different values? It seems like you wouldn't get to it until the last time printBackward returns, and 'head' at that point would be 3, which is the first number printed. But doesn't it stop at this point? Where do 2 and 1 come from? Thanks! From ask at me Mon Mar 27 20:40:50 2006 From: ask at me (AndyL) Date: Mon, 27 Mar 2006 20:40:50 -0500 Subject: what is the the best way to express following: Message-ID: <_uOdnaBMCLmcPLXZRVn-uA@comcast.com> if type(key).__name__ == "int" or type(key).__name__ == "long": abc() elif type(key).__name__ == "str": efg() elif type(key).__name__ == "tuple" or type(key).__name__ == "list": ijk() In other words I need to determinie intiger type or string or []/() in elegant way, possibly without or ... Thx, A. From amichail at gmail.com Sun Mar 19 07:11:52 2006 From: amichail at gmail.com (Amir Michail) Date: 19 Mar 2006 04:11:52 -0800 Subject: python library for web discussions References: <1142753598.098579.14080@z34g2000cwc.googlegroups.com> <1142769264.602398.55980@z34g2000cwc.googlegroups.com> Message-ID: <1142770312.155304.147740@e56g2000cwe.googlegroups.com> Gregory Petrosyan wrote: > reddit is written with webpy (webpy.org), maybe you should give it a > try? I'm looking for a library that provides commenting on items in a similar way to reddit/digg/slashdot. I would rather not write all that code from scratch. I don't think web.py comes with that functionality, although of course, some free package may provide it on top of web.py. Amir From kent at kentsjohnson.com Thu Mar 16 06:03:46 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 16 Mar 2006 06:03:46 -0500 Subject: Install Universal Encoding Detector In-Reply-To: <1142503299.223649.76260@j52g2000cwj.googlegroups.com> References: <1142430310.530681.321760@i39g2000cwa.googlegroups.com> <1142503299.223649.76260@j52g2000cwj.googlegroups.com> Message-ID: <4419411d$1_3@newspeer2.tds.net> Jacob wrote: > How do I uninstall? Delete the chardet folder from site-packages (Python24\Lib\site-packages on Windows, not sure of the exact path on other OS's). Kent From sybrenUSE at YOURthirdtower.com.imagination Wed Mar 22 08:22:45 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 22 Mar 2006 14:22:45 +0100 Subject: Some info References: <1142610889.512781.69650@j33g2000cwa.googlegroups.com> <1142977513.263383.88410@i39g2000cwa.googlegroups.com> <4420909E.3080208@v.loewis.de> Message-ID: Fulvio enlightened us with: > Now, I'd like to go some step farther and make a disk cataloger. What kind of disk? Harddisks? DVDs? Audio CDs? > I'm, actually, a bit stuck on how to collect informations regarding > disk names (CDroms or USB HDs). Depends on what names you want. Filenames? Track names? Artist names? Filesystem labels? 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 Bob.Capa at gmail.com Tue Mar 7 11:14:47 2006 From: Bob.Capa at gmail.com (Bob.Capa at gmail.com) Date: 7 Mar 2006 08:14:47 -0800 Subject: SOAPpy, WSDL and objects Message-ID: <1141748087.777107.262340@z34g2000cwc.googlegroups.com> Hi, I am trying to access a webservice which needs a login request of the following form: FirstName LastName I am trying to do this with the following code: from SOAPpy import WSDL server = WSDL.Proxy(m_url) request = {'firstname': FirstName, 'lastname': LastName} server.login(request) But this will be sending the following: FirstName LastName Basically, I need to know how to change the code so it generates 'request' instead of 'v1'. Have a nice evening! From fredrik at pythonware.com Tue Mar 14 07:37:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Mar 2006 13:37:00 +0100 Subject: andmap and ormap References: <1142339035.687474.271120@p10g2000cwp.googlegroups.com> <1142339421.5045.3.camel@kenshin> Message-ID: Felipe Almeida Lessa wrote: > The problem is that it will evaluate all possibilities needlessly. Try > (not tested and 2.4-only): footnote: if you have a recent Python 2.5 build, you can make them even shorter: >>> help(any) any(...) any(iterable) -> bool Return True if bool(x) is True for any x in the iterable. >>> help(all) all(...) all(iterable) -> bool Return True if bool(x) is True for all values x in the iterable. From kay.schluehr at gmx.net Sat Mar 11 08:21:14 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 11 Mar 2006 05:21:14 -0800 Subject: Cheese Shop -> BSOL? In-Reply-To: <1142076162.193533.80540@v46g2000cwv.googlegroups.com> References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> <1142039514.707128.240270@j33g2000cwa.googlegroups.com> <1142076162.193533.80540@v46g2000cwv.googlegroups.com> Message-ID: <1142083273.968416.151140@p10g2000cwp.googlegroups.com> Paul Boddie wrote: > Tim Churches wrote: > > Would it be possible to rename "Cheese Shop" as "Bright Side of Life"? > > Well, you could replay the conversation I gave as an example elsewhere > to see if it sounds ridiculous or not, but what we've encountered here > is the problem of whether something should be given a distinctive > identity or a derivative identity. A long time ago, and possibly > continuing to this day, people complained about how nearly every Python > package, module or program had names starting or ending with "Py" - > announcing a module in a Python newsgroup and giving it a name starting > with "Py" seemed somewhat redundant, and there was always the issue of > not being able to scan long lists of packages comfortably, just like > with all the KDE application names that start with the letter K. > > But even without "the curse of Py", many people don't just choose > arbitrary names for their packages: it often makes sense to include > related technologies in the name (eg. XML, XSLT, ado, dav), or to use a > descriptive component, possibly in shortened form (eg. auth, bayes, > bio, Cal). Yes, a search will often bring forth the right resource > regardless of what it's called, but many people underestimate their own > searching skills and overestimate what other people can find via things > like Google. > > Of course, programs may downplay Python as the implementation > technology because the underlying technical details are mostly > irrelevant to end-users (eg. BitTorrent, b3, Eric, Glarf), but if we > look at distinctively named packages, we can see that they often > attempt to define their own identity distinct from Python (eg. > BeautifulSoup, Dabo, DejaVu, Django, Twisted, Zope), frequently because > they seek to be the primary point of reference for developers - > developing in Twisted or Zope is more specialised than just developing > things in Python. Some of the distinctively named package names employ > metaphors and/or cultural references that possibly make them more > memorable, but they don't necessarily make the names easy to guess. > > So should a service for finding Python packages have a distinct > identity? It is possible that a package index could be someone's > principal view of the Python world ("I go to Camelot to get... what is > it I get there?"), but the things that emerge from such a service > aren't just downloads that have little in common with each other. > Consequently, I don't think a descriptive name, derived from the name > of the technology, is sensibly avoided in this case. > > Paul The problem I have with the cheese-shop is less a naming but a usability issue. In some commercial projects that involve Python I already integrated SQLite as a local database for storing and retrieving all kind of configuration data as well as session data, failure statistics etc. I also extended a Python console in order to send SQL commands directly using this syntax "$ select * from reports where...". I should mention that this kind of integration was one of the most acknowledged features by those who where Python sceptics. I wonder if creating a database client, integreting it with a Python console and shipping it with a Python setup would not leave behind all other solutions in the field? BTW I'm not only intererested in the functionality of a package but how well it performs how well it is tested etc. The packages checked into the cheese-shop obtain already a rough classification. If classification schemes become more usable it is likely that they could be extended. Kay From jrivero at python.org.ve Tue Mar 21 17:21:12 2006 From: jrivero at python.org.ve (Jesus Rivero - (Neurogeek)) Date: Tue, 21 Mar 2006 18:21:12 -0400 Subject: nested for loops In-Reply-To: References: Message-ID: <44207C58.805@python.org.ve> It is, but range(2,2) doesn't do anything Jesus Rivero - Neurogeek John Salerno wrote: >Can someone tell me why 'n' in this example isn't 2? > > >>> for n in range(2, 10): > for x in range(2, n): > print 'x =', x, 'n =', n > > >x = 2 n = 3 > > From caleb.hattingh at gmail.com Fri Mar 17 15:18:35 2006 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 17 Mar 2006 12:18:35 -0800 Subject: Use of Python with GDAL. How to speed up ? In-Reply-To: <1142590123.885456.67240@e56g2000cwe.googlegroups.com> References: <1142590123.885456.67240@e56g2000cwe.googlegroups.com> Message-ID: <1142626715.861091.86190@e56g2000cwe.googlegroups.com> Hi The documentation for the python profiler in the python library reference is extremely readable (well done James Roskin!?). Profile your code, and when you find where the speed problem occurs, try pitching just that section of code in comp.lang.python. You will likely get much feedback. Everyone loves small optimization exercises, and there be bots here who get the optimal solution on the first try. Though I would like to (seems an interesting application), I don't have time available to go through all your code now. Thanks Caleb From kent at kentsjohnson.com Mon Mar 6 20:14:12 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 06 Mar 2006 20:14:12 -0500 Subject: Does '#hash' mean anything in IDLE? In-Reply-To: <7xoe0jgpbu.fsf@ruckus.brouhaha.com> References: <1141331534.634181.275880@p10g2000cwp.googlegroups.com> <1141332159.625375.40540@e56g2000cwe.googlegroups.com> <3TINf.1719$No6.40137@news.tufts.edu> <1141394786.531934.134920@t39g2000cwt.googlegroups.com> <1141405501.950172.54370@i39g2000cwa.googlegroups.com> <4408a0d6$1@nntp0.pdx.net> <7xk6bb45tf.fsf@ruckus.brouhaha.com> <4408bfd9$1@nntp0.pdx.net> <7xoe0jgpbu.fsf@ruckus.brouhaha.com> Message-ID: <440cd99f$1_1@newspeer2.tds.net> Paul Rubin wrote: > Scott David Daniels writes: >>Using a variant of DSU (Decorate-Sort-Undecorate) with max for S, >>rather than sort: >> >> print max((len(words), words) for words in d.itervalues()) >>or: >> size, words = max((len(words), words) for words in d.itervalues()) >> print size, sorted(words) > > > That's nice and concise but it doesn't completely fix the running time > issue. max(words, key=len) should run in O(N) time where N is the > number of words, but > max((len(words), words) for words in d.itervalues()) > might need time proportional to the total lengths of the words. I.e. > suppose words=['aaaaaaaa','aaaaaaab','aaaaaaac']. They are the same > length so the cmp builtin proceeds to the next component of the tuples > being compared. That means the strings get compared character by > character. That's maybe not too bad for dictionary words, but isn't > too great for arbitrary strings which might be millions of chars each. use max((len(words), i, words) for i, words in enumerate(d.itervalues())) The index will always disambiguate and words will never be compared. > > In general that DSU pattern doesn't even always work: you might want > the max of objects which don't directly support any comparison methods > that the cmp builtin understands. Using the index as above prevents the objects from ever being compared. Kent From jodansmif at gmail.com Thu Mar 16 19:58:38 2006 From: jodansmif at gmail.com (jodansmif at gmail.com) Date: 16 Mar 2006 16:58:38 -0800 Subject: accessing a USB HID Message-ID: <1142557118.268666.108770@e56g2000cwe.googlegroups.com> I've been teaching myself Python as part of my senior design project at university. The obstacle our group currently faces is communicating with a microcontroller (ACS USB Servo II) that appears in Windows as a USD HID. Unfortunately, the vendor's sample code is in Visual Basic and Visual C++ which none of our group members have any experience using. My hope is that someone has experience with this type of problem and can point me to some reference material. At this point I'm a bit lost in the morass of USB terminology. While I'm at it... if anyone knows of a better way to approach this problem (serial or parallel microcontroller) or another language with better tools, I'd appreciate that as well. We're just trying to turn several motors on and off while polling some photodiodes and all this HID business seems like unnessary overkill. Any assistance much appreciated, Jordan From sa-spamnothanks- at nsl.com Thu Mar 16 17:41:14 2006 From: sa-spamnothanks- at nsl.com (sa) Date: Thu, 16 Mar 2006 22:41:14 GMT Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> Message-ID: in k: cp:{[c;n;p]+(n#c)_vs(!_ c^n)_dvl,/{2_sv+(,/,/:\:)/(),/:@[x;&x=-1;:[;!c]]}'p} examples: cp[2;3;,0 -1 1] (0 0 0 0 1 0 1 0 0 1 0 1 1 1 0 1 1 1) cp[2;3;(0 -1 1;1 -1 0)] (0 0 0 0 1 0 1 0 1 1 1 1) cp[2;3;(0 -1 1;1 -1 1)] (0 0 0 0 1 0 1 0 0 1 1 0) arguments of cp: c = cardinality of the input set n = power p = list of patterns (-1 = wildcard) the algorithm directly computes the target set. in other words, it does not generate the set, then filter the matches from the target. modifying cp to accept s instead of the cardinality of s, patterns expressed in terms of elements of s, &c. adds nothing of interest to the problem. wrote in message news:1142507663.796075.212430 at v46g2000cwv.googlegroups.com... > The python code below generates a cartesian product subject to any > logical combination of wildcard exclusions. For example, suppose I want > to generate a cartesian product S^n, n>=3, of [a,b,c,d] that excludes > '*a*b*' and '*c*d*a*'. See below for details. > > CHALLENGE: generate an equivalent in ruby, lisp, haskell, ocaml, or in > a CAS like maple or mathematica. > > #------------------------------------------------------------------------------- > # Short algorithm description > # using function _genAll the program generates > # cartesian product without sets, which match > # some wildcarts > # Sets generation uses recursion -> > # first of all sets will be generated with dimension 1 and than > filtered through wildcarts > # then sets will be generated with dimension 2 and filtered again > # until the required set dimension is reached > # Program avoids explicit generation of some part of CP sets > # if the end of whildcart is asterics (*) and if the first part of > whildcart (without astrics) > # matches current set => then this set will be filtered out and won't > be used in > # higher dimension set generation > # example *,1,*,2,* [1,2] dim = 10 > # by dimension 2 only arrays [1,1],[2,1],[2,2] are will be generated > # => array [1,2] won't be used in next recursion levels > #------------------------------------------------------------------------------- > # To obtaine result use function > # CPWithoutWC first parameter is a list of any elements > (char,int,string,class exemplar ,.... any type) > # secont param is CP dimension > # other parameters are wildcarts => lists with any values then may > include > # special value ALL - asterics equivalent > #Example of usage: command line > # >>> import cartesianProduct as cp > # >>> for i in cp.CPWithoutWC([1,2],3,[1,cp.ALL,2]): > # print i > # [1, 1, 1] > # [1, 2, 1] > # [2, 1, 1] > # [2, 1, 2] > # [2, 2, 1] > # [2, 2, 2] > # >>> for i in > cp.CPWithoutWC(['a','b'],3,['a',cp.ALL,'b'],['b',cp.ALL,'a']): > # print i > # ['a', 'a', 'a'] > # ['a', 'b', 'a'] > # ['b', 'a', 'b'] > # ['b', 'b', 'b'] > # >>> for i in cp.CPWithoutWC([1,2],3,[1,cp.ALL,2],[2,cp.ALL,1]): > # print i > # [1, 1, 1] > # [1, 2, 1] > # [2, 1, 2] > # [2, 2, 2] > # >>> > # >>> for i in cp.CPWithoutWC([1,2],121212,[1,cp.ALL],[2,cp.ALL,1]): > # print i > ## execute immediately > # >>> > # if You don't want to print cp. before ALL and CPWithoutWC use import > like this: > # from cartesianProduct import ALL,CPWithoutWC > # CPWithoutWC is a python generator. Which means that it returns values > > # immediately and generate next in next cycle. > # Program example > # > ## from cartesianProduct import ALL,CPWithoutWC > ## def main(): > ## for i in > cp.CPWithoutWC(['a','b'],3,['a',cp.ALL,'b'],['b',cp.ALL,'a']): > ## ## do what You want with current value > ## ......... > ## ## go back to for statement and generate new > ## if __name__ == "__main__": > ## main() > # > """ > Using logical combinations of WC: > 1) It's possible to pass on to the function CPWithoutWC > any number of wildcarts after first two parameters, for example: > CPWithoutWC([1,2],121212,[1,cp.ALL],[2,cp.ALL,1],...) > where ... - is any other wildcart's additional function parameters. > Number of additional WC is not limited. > Function will filter out all combinations, which match any passed on > WC. > It's equal to WC1 | WC2 | .... , where | is python analog of OR > logical operations. > 2) To use more complex WC combinations follow these steps > a) First of all create all needed WC > b) Then use operators |, & and braces () to create combinations > required and then pass it on to function > CPWithoutWCEx as the third parameter. Don't use "or" and "and" > python statement, otherwise program will > work improper. First two parameters of this function are the same as > of CPWithoutWC function - set of > elements and CP dimension. An example of what was described above in > command line: > >>> from cartesianProduct import ALL,CPWithoutWC,CPWithoutWCEx,WC > >>> a = WC([ALL,1,ALL]) > >>> b = WC([ALL,2,ALL]) > >>> c = a & b #filter out all sets which match a and b > >>> for i in CPWithoutWCEx([1,2],3,c) : print i > [1, 1, 1] > [2, 2, 2] > >>> # all sets where both 1 and 2 are present will be filtered out > >>> d = a | b > >>> for i in CPWithoutWCEx([1,2],3,d) : print i > >>> # returns nothing > >>> for i in CPWithoutWCEx([1,2,3],3,d) : print i > [3, 3, 3] > >>> a = WC([2,1,ALL]) > >>> b = WC([1,2,ALL]) > >>> c = WC([ALL,2]) > >>> d = ( a | b ) & c > >>> for i in CPWithoutWCEx([1,2],3,d) : print i > [1, 1, 1] > [1, 1, 2] > [1, 2, 1] > [2, 1, 1] > [2, 2, 1] > [2, 2, 2] > >>> # filters out all combinations which start with [1,2] or [2,1] > and end with 2 > > Number of WC, which are used to form logical combinations is not > limited. > """ > """ > 13.02.2006 > a)Two new function - CPWithoutWCEx_L and CPWithoutWC_L are added. > Their interface is the same as of CPWithoutWCEx and CPWithoutWC > accordingly, except that the third parameter is WC list and > they accept strictly three parameters. > > As You can see these functions are very simple because > python is quite flexible => > >>> def s(x,y): return x * y > >>> d = [3,2] > >>> s(*d) ## == s(3,2) > 6 > > b)Now WC can take string as parameter, and You can use string > as parameters of functions CPWithoutWC and CPWithoutWC_L > instead of WC lists. > Strings transform into WC according to these rules > 1)If first symbol in the string is > alphanumeric (a-z or A-Z or 0-9) or '*' > character the every character of the string will be recognized as > a distinct set element. Examples: > "ad*d*" == ['a','d',cp.ALL,'d',cp.ALL] > "*A*b3*%^('" == [cp.ALL,'A',cp.ALL.'b','3',cp.ALL,'%','(',"'"] > 2)If first character is not (alphanumeric or '*') > it will be treated as a delimitator. Examples: > ":a:A:1:*" == ['a','A','1',cp.ALL] > ":aA1:*" == ['aA1',cp.ALL] > it's not necessary to write delimitators around the asterics > ":aA1*" == ['aA1',cp.ALL] > "%aA%1*" == ['aA','1',cp.ALL] > 3)If all non delimit and non asterics character in elements > are digits => they will be treated as numbers.Examples: > "123*" == [1,2,3,cp.ALL] > ":12:3*" == [12,3,cp.ALL] > but > ":12:a:3*" == ['12','a','3',cp.ALL] > Examples of use: > >>> for i in cp.CPWithoutWC(['a','b'],3,'a*b','b*a'): > print i > ['a', 'a', 'a'] > ['a', 'b', 'a'] > ['b', 'a', 'b'] > ['b', 'b', 'b'] > >>> for i in cp.CPWithoutWC_L(['a','b'],3,['a*b','b*a']): > print i > ['a', 'a', 'a'] > ['a', 'b', 'a'] > ['b', 'a', 'b'] > ['b', 'b', 'b'] > #You can mixe strings and lists for wildcarts > >>> for i in cp.CPWithoutWC_L(['a','b'],3,['a*b',['b',cp.ALL,'a']]): > print i > ['a', 'a', 'a'] > ['a', 'b', 'a'] > ['b', 'a', 'b'] > ['b', 'b', 'b'] > >>> for i in cp.CPWithoutWC_L(['abc','xyz'],3,[':abc*xyz']): > print i > ['abc', 'abc', 'abc'] > ['abc', 'xyz', 'abc'] > ['xyz', 'abc', 'abc'] > ['xyz', 'abc', 'xyz'] > ['xyz', 'xyz', 'abc'] > ['xyz', 'xyz', 'xyz'] > """ > #------------------------------------------------------------------------------- > class ALL(object):pass > #------------------------------------------------------------------------------- > class NO_ONE(object):pass > #------------------------------------------------------------------------------- > class BFunctor(object): > def __init__(self,func): > self.func = func > def __call__(self,*dt,**mp): > return self.func(*dt,**mp) > @classmethod > def OR(cls,x,y): > return cls(lambda *dt,**mp : x(*dt,**mp) | y(*dt,**mp)) > @classmethod > def AND(cls,x,y): > return cls(lambda *dt,**mp : x(*dt,**mp) & y(*dt,**mp)) > > #----------------------------------------------------------------------------- > def __or__(self,x): > return BFunctor.OR(self,x) > > #----------------------------------------------------------------------------- > def __and__(self,x): > return BFunctor.AND(self,x) > #------------------------------------------------------------------------------- > def _genAll(head,n,WCF,curr): > if len(curr) != 0 and n != 0: > for i in curr: > nhead = head + [i] > if n != 1 : > # needed dimension are not reached > # -> we mast tell WC that some other values > # may concatenate in the end of nhead in next recursion levels > # but if WC is ended with asterics (ALL), than dosn't matter > # so i use special walue NO_ONE to resolve this problem > # if WC with final asterics like [1,2,3,ALL] are matched nhead > => > # they matched nhead + [NO_ONE] to > # but if WC is like [1,ALL,2,3] => they dont match > [1,2,3,NO_ONE] => > # they don't prevent to generate [1,2,3,4] on next recursion > level > x = WCF(nhead + [NO_ONE],curr) > else : x = WCF(nhead,curr) > if False == x: > if n == 1 : yield nhead > else: > for i in _genAll(nhead,n - 1,WCF,curr): > yield i > elif n == 0 : > yield head > #------------------------------------------------------------------------------- > class WC(object): > def __init__(self,wc): > self.wc = wc > self.transformWC() > self.num_els = 0 > self.compress() > self.comphdr = None > self.findMaxHeader() > self.ln = len(self.wc) > > #----------------------------------------------------------------------------- > def transformWC(self): > if self.wc.__class__ not in (str,unicode) : return > if len(self.wc) == 0 : return > if self.wc[0].isalnum() or self.wc[0] == "*": > wc = self.wc > else: > wc = self.wc[1:].split(self.wc[0]) > nwc = [] > for i in wc: > if i == '*' : nwc.append(ALL) > elif '*' in i : > for j in i.split('*'): > if j : nwc.append(j) > nwc.append(ALL) > del nwc[-1] > else : nwc.append(i) > #check if all elements are numbers or * > allnum = True > for i in nwc: > if i is ALL : continue > try : int(i) > except : > allnum = False > break > if allnum: > for i,j in enumerate(nwc): > if j is not ALL: > nwc[i] = int(j) > self.wc = nwc > > #----------------------------------------------------------------------------- > def findMaxHeader(self): > return > > #----------------------------------------------------------------------------- > def compress(self): > "delete dublicated * values" > if len(self.wc) == 0 : return > wc_ = self.wc[:1] > for i in self.wc[1:]: > if i == ALL and i == wc_[-1] : continue > wc_.append(i) > self.wc = wc_ > > #----------------------------------------------------------------------------- > def matchExact(self,hd,pos = 0): > if pos == len(self.wc) : return len(hd) == 0 > if self.wc[pos] == ALL : > if pos + 1 == len(self.wc) : return True > vl = self.wc[pos + 1] > cpos = -1 > while True: > try : cpos = hd.index(vl,cpos + 1) > except : return False > if self.matchExact(hd[cpos + 1:],pos + 2) : return True > else: > if len(hd) == 0 : return False > if hd[0] != self.wc[pos] : return False > return self.matchExact(hd[1:],pos + 1) > > #----------------------------------------------------------------------------- > def __or__(self,x): > return BFunctor.OR(self,x) > > #----------------------------------------------------------------------------- > def __and__(self,x): > return BFunctor.AND(self,x) > > #----------------------------------------------------------------------------- > def __call__(self,hd,st): > return self.matchExact(hd) > #------------------------------------------------------------------------------- > def CPWithoutWCEx(set,n,wc): > for i in _genAll([],n,wc,set) : > yield i > #------------------------------------------------------------------------------- > def CPWithoutWC(set,n,*dt): > if len(dt) == 0 : > wc = lambda hd,st : True > else: > wc = WC(dt[0]) > #print wc.wc > for i in dt[1:]: > wc = wc | WC(i) > for i in _genAll([],n,wc,set) : > yield i > #------------------------------------------------------------------------------- > def CPWithoutWC_L(set,n,WCs): > for i in CPWithoutWC(set,n,*WCs): > yield i > #------------------------------------------------------------------------------- > def CPWithoutWCEx_L(set,n,WCs): > for i in CPWithoutWCEx(set,n,*WCs): > yield i > #------------------------------------------------------------------------------- > def main(): > for i in CPWithoutWC_L(['abc','xyz'],3,[':abc*xyz']): > print i > #------------------------------------------------------------------------------- > if __name__ == "__main__" : main() > #------------------------------------------------------------------------------- > From bearophileHUGS at lycos.com Thu Mar 9 15:42:41 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 9 Mar 2006 12:42:41 -0800 Subject: First script, please comment and advise In-Reply-To: References: <1141917596.011498.311500@p10g2000cwp.googlegroups.com> Message-ID: <1141936961.472567.53070@p10g2000cwp.googlegroups.com> > nested and hided inside a class. Hidden, sorry :-) >Can a "sub-function" be called directly from outside the defining function? I don't think you can access a nested function in a clean&nice way (and you can nest classes too, etc). With a little of Python magic maybe there is a way to do it... But for such purposes probably a module (or maybe a class with a static method) is better. Bye, bearophile From bencvt at gmail.com Sat Mar 18 23:25:59 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 18 Mar 2006 20:25:59 -0800 Subject: Can I use a conditional in a variable declaration? References: <1142741039.554379.182170@g10g2000cwb.googlegroups.com> Message-ID: <1142742359.851904.66040@u72g2000cwu.googlegroups.com> volcs0 at gmail.com wrote: > I've done this in Scheme, but I'm not sure I can in Python. > > I want the equivalent of this: > > if a == "yes": > answer = "go ahead" > else: > answer = "stop" > > in this more compact form: > > > a = (if a == "yes": "go ahead": "stop") > > > is there such a form in Python? I tried playing around with lambda > expressions, but I couldn't quite get it to work right. There will be, in Python 2.5 (final release scheduled for August 2006): >>> answer = "go ahead" if a=="yes" else "stop" See: http://mail.python.org/pipermail/python-dev/2005-September/056846.html http://www.python.org/doc/peps/pep-0308/ --Ben From steve at REMOVEMEcyber.com.au Thu Mar 30 03:46:47 2006 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 30 Mar 2006 18:46:47 +1000 Subject: any() and all() on empty list? References: Message-ID: <442B9AF7.2010407@REMOVEMEcyber.com.au> Tim Peters wrote: >>In the all() example, if there *are* no values in S, then none of the >>values can be != 0, and IMHO all() should return False. > > > That would break everything mentioned above. Think of it another way: > if all(seq) is false, shouldn't it be the case that you can point to > a specific element in seq that is false? Think of it this way: if all(seq) is true, shouldn't it be the case that you can point to a specific element in seq that is true? It may be that all([]) => True is useful more often than all([]) => False would be, in the same way that it is useful to define 0! = 1 and other mathematical identities, but that doesn't imply that, strictly speaking, there isn't some monkey-business going on there. Now, I'm happy to admit that this is useful monkey-business, but it can still lead to unexpected results, as in my example in a previous post. -- Steven. From godoy at ieee.org Fri Mar 3 23:19:38 2006 From: godoy at ieee.org (Jorge Godoy) Date: Sat, 04 Mar 2006 01:19:38 -0300 Subject: stripping spaces in front of line References: <1141444890.389188.140870@i40g2000cwc.googlegroups.com> Message-ID: <87lkvq96zp.fsf@ieee.org> eight02645999 at yahoo.com writes: > hi > wish to ask a qns on strip > i wish to strip all spaces in front of a line (in text file) > > f = open("textfile","rU") > while (1): > line = f.readline().strip() > if line == '': > break > print line > f.close() > > in "textfile", i added some spaces in and then ran the code, it prints > out the lines without the spaces in front. I double checked "textfile" > and it does contains some lines with spaces in front. > Is it true that "readline().strip()" perform the removing of spaces in > front of a line as well? Is it documented anywhere? > I am using Windows environment. thanks jupiter:~ $ pydoc string.strip Help on function strip in string: string.strip = strip(s, chars=None) strip(s [,chars]) -> string Return a copy of the string s with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping. -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From grflanagan at yahoo.co.uk Fri Mar 24 09:08:59 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 24 Mar 2006 06:08:59 -0800 Subject: overlapping sets In-Reply-To: <1143183343.525253.251430@i39g2000cwa.googlegroups.com> References: <1143183343.525253.251430@i39g2000cwa.googlegroups.com> Message-ID: <1143209339.844883.75940@i39g2000cwa.googlegroups.com> kpp9c wrote: > I have a question... and ... whew ... i am gonna be honest, i haven't > the slightest clue how to even start ... i am not sure if i used up all > my good will here or can take a mulligan.. i love to try to at least > post some lame broken code of my own at first... but like i said, not > being a math person i am not even sure how to start or if it is even > possible. > > here's the deal... i have a dictionary that defines some collections.. > like so: > > sets = { ('one') : [0, 4, 7, 9 ], > ('two') : [0, 3, 7, 9 ], > ('three') : [0, 4, 7, 11], > ('four') : [0, 3, 7, 10 ], > ('five') : [0, 4, 7, 10 ], > ('six') : [0, 4, 8, 10 ], > ('seven') : [0, 3, 6, 10], > ('eight') : [0, 3, 6, 9 ], > ('nine') : [0, 3, 7, 11 ], > ('ten') : [0, 5, 7, 10 ] } > > I every time i call this function i would like like it to return a > collection at random, any collection, so long as it has all but one > element that is the same. So if i grab [0, 4, 7, 9 ] as my first set > my next set could be: [0, 3, 7, 9 ], or [0, 4, 8, 9 ], or [0, 4, 7, > 10], or [1, 4, 7, 9 ], since all these sets contain 3 elements in > common with the first, and only one that is new or different... but if > my first run give me: [0, 4, 7, 9 ] i would not get [0, 5, 7, 10 ], > since this is set has 2 elements that are unique. The goal it to move > from set to set to set to set always with a maximum of overlap & common > elements. > probably not very efficient but I think it roughly does what you want. (maybe add a boolean 'sort' parameter, to select sorted output or not): # k is the length of the required output lists, 0 References: <1143128619.670174.282160@t31g2000cwb.googlegroups.com> Message-ID: <1143226189.547274.90720@t31g2000cwb.googlegroups.com> How about we all get tatoos? : ) Robert From neurogasm at gmail.com Sat Mar 18 17:24:05 2006 From: neurogasm at gmail.com (Kevin F) Date: Sat, 18 Mar 2006 17:24:05 -0500 Subject: POP3 Mail Download In-Reply-To: <7g1p12ttfcf1sd5v9rrggr6ioushs2e1id@4ax.com> References: <7g1p12ttfcf1sd5v9rrggr6ioushs2e1id@4ax.com> Message-ID: Dennis Lee Bieber wrote: > On Sat, 18 Mar 2006 16:44:44 -0500, Kevin F > declaimed the following in comp.lang.python: > > >> However, if I try to actually download the messages themselves, my >> python editor highlights 'msgSize' and says "invalid syntax" when I run >> the following subsequent lines of code: >> >> >> ------------------------ >> emails = [] >> for msg in messagesInfo: >> msgNum = int(split(msg, " ")[0] >> msgSize = int(split(msg, " ")[1] >> if(msgSize < 20000): >> messages = server.retr(msgNum)[1] >> messages = join(message, "\n") >> emails.append(message) > > Look very closely at your indentation > > I fixed the indentation to: emails = [] for msg in messagesInfo: msgNum = int(split(msg, " ")[0] msgSize = int(split(msg, " ")[1] if(msgSize < 20000): messages = server.retr(msgNum)[1] messages = join(message, "\n") emails.append(message) and it still doesn't work, what's wrong? From s99999999s2003 at yahoo.com Sat Mar 4 11:54:33 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 4 Mar 2006 08:54:33 -0800 Subject: spliting on ":" Message-ID: <1141491273.776287.66070@j33g2000cwa.googlegroups.com> hi i have a file with xxx.xxx.xxx.xxx:yyy xxx.xxx.xxx.xxx:yyy xxx.xxx.xxx.xxx:yyy xxx.xxx.xxx.xxx xxx.xxx.xxx.xxx xxx.xxx.xxx.xxx:yyy i wanna split on ":" and get all the "yyy" and print the whole line out so i did print line.split(":")[-1] but line 4 and 5 are not printed as there is no ":" to split. It should print a "blank" at least. how to print out lines 4 and 5 ? eg output is yyy yyy yyy yyy thanks From s323 at mail.ru Thu Mar 2 08:21:39 2006 From: s323 at mail.ru (Sergey) Date: Thu, 2 Mar 2006 16:21:39 +0300 Subject: why? [win32com/WMI] References: Message-ID: "Tim Golden" wrote in message news:mailman.2606.1141304051.27775.python-list at python.org... [Sergey] >| >import wmi >| >c = wmi.WMI (computer="srv", user="Admin at zzz.ru", password="****") >| >pid, retval = c.Win32_Process.Create (CommandLine="notepad.exe") >| >| Wonderful... It works. >Also, in case you haven't, have a look at the cookbook page: >http://timgolden.me.uk/python/wmi_cookbook.html >which has several useful examples. Yes, I had run it. And, just now I updated python, pythonwin and wmi.py to latest version. And got: >>> a=wmi.WMI() >>> a.Win32_Process.Create(CommandLine="notepad.exe") # --- it works >>> a.Win32_Process.new().Create(CommandLine="notepad.exe") # it still fail Traceback (most recent call last): File "", line 1, in ? File "wmi.py", line 361, in __call__ handle_com_error (error_info) File "wmi.py", line 208, in handle_com_error raise x_wmi, "\n".join (exception_string) wmi.x_wmi: -0x7ffdfff7 - Exception occurred. Error in: SWbemObjectEx -0x7ffbefff - Generic failure Without 'new' everything works. And does everything I need from it. And, I have another question. Is there way to access WMI from linux? From jon+usenet at unequivocal.co.uk Tue Mar 21 06:02:51 2006 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 21 Mar 2006 11:02:51 GMT Subject: why isn't Unicode the default encoding? References: <441F21D7.6000005@v.loewis.de> <441f3f4f$0$29501$9b622d9e@news.freenet.de> Message-ID: In article <441f3f4f$0$29501$9b622d9e at news.freenet.de>, Martin v. L?wis wrote: > In any case, it doesn't matter what encoding the document is in: > read(2) always returns two bytes. It returns *up to* two bytes. Sorry to be picky but I think it's relevant to the topic because it illustrates how it's difficult to change the definition of file.read() to return characters instead of bytes (if the file is ready to read, there will always be one or more bytes available (or EOF), but there won't always be one or more characters available). From ygao2004 at gmail.com Tue Mar 21 23:57:24 2006 From: ygao2004 at gmail.com (ygao) Date: 21 Mar 2006 20:57:24 -0800 Subject: apache config file parser In-Reply-To: <1142693998.104376.141020@v46g2000cwv.googlegroups.com> References: <1260498.qhR4XvVnDh@teancum> <1142693998.104376.141020@v46g2000cwv.googlegroups.com> Message-ID: <1143003444.255672.252880@i40g2000cwc.googlegroups.com> Can ZConfig write apache conf file? From greg.kujawa at gmail.com Tue Mar 21 13:46:28 2006 From: greg.kujawa at gmail.com (gregarican) Date: 21 Mar 2006 10:46:28 -0800 Subject: Can XML-RPC performance be improved? References: <1142962694.368445.43780@t31g2000cwb.googlegroups.com> Message-ID: <1142966788.916967.213180@i39g2000cwa.googlegroups.com> Skip wrote: > I don't know about the OP, but in my case it was a drop-dead simple > cross-language RPC protocol. Exactly. RPC implementations. Typically these are a quick "do this with this" sent from the client, with a brief "okay, I did that, here's the result" back from the server. Shovelling huge amounts of data using any XML encapsulation leads to a certain code smell at the very least. From ed.whyatt at gmail.com Wed Mar 22 11:31:16 2006 From: ed.whyatt at gmail.com (EdWhyatt) Date: 22 Mar 2006 08:31:16 -0800 Subject: Server.sendmail with no "to_addrs" parameter. In-Reply-To: <1143040642.425775.47000@v46g2000cwv.googlegroups.com> References: <1143026321.129185.109310@j33g2000cwa.googlegroups.com> <1143040642.425775.47000@v46g2000cwv.googlegroups.com> Message-ID: <1143045076.369743.146060@u72g2000cwu.googlegroups.com> So it's a restriction of Python? What I am trying to simulate here is the sending of mail to addresses solely in the CC and/or BCC fields - both of which are possible through Outlook. From bearophileHUGS at lycos.com Mon Mar 6 16:44:41 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Mar 2006 13:44:41 -0800 Subject: IronPython on Shootout Message-ID: <1141681481.219194.178320@j52g2000cwj.googlegroups.com> I have suggested the Shootout site to add tests for IronPython too (tests are done on Mono): http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=iron People that use IronPython can probably fix some of those programs. Bye, bearophile From johnjsal at NOSPAMgmail.com Sun Mar 5 00:45:06 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 05 Mar 2006 00:45:06 -0500 Subject: question about sys.exc_type and sys.exc_value In-Reply-To: <1141531498.397372.77600@u72g2000cwu.googlegroups.com> References: <8oidnS4envM7oZfZRVn-pg@rcn.net> <1141531498.397372.77600@u72g2000cwu.googlegroups.com> Message-ID: David Wahler wrote: > Are you using the first edition of "Learning Python"? According to > that was published in 1999, > which puts it right around the end of Python 1.5. I'd strongly suggest > you find a much more recent tutorial, as a lot of python has been > improved and altered since then (sometimes in incompatible ways). Actually I'm using the second edition, which is updated to 2.2/2.3. But you are right, I just tried it in the command prompt and it does work, so my mind can rest tonight. :) From siasookhteh at gmail.com Thu Mar 23 22:08:56 2006 From: siasookhteh at gmail.com (siasookhteh at gmail.com) Date: 23 Mar 2006 19:08:56 -0800 Subject: Strings and % sign fails - Help Please In-Reply-To: <87lkv0r1lk.fsf@ieee.org> References: <1143168531.461348.130160@t31g2000cwb.googlegroups.com> <87lkv0r1lk.fsf@ieee.org> Message-ID: <1143169736.507783.95460@z34g2000cwc.googlegroups.com> heh.. It works except I am using psycopg.Binary(somebinarystructure), and I am not really doing it by hand to just add the extra %, and psycopg.Binary doesn't do it. I'd imagine it's a bug with psycopg package. Any quick way to project a string from freak '%' problems? Thanks, Sia Jorge Godoy wrote: > siasookhteh at gmail.com writes: > > > The following statement fails because it has the '%' sign in it. > > cursor.execute("select '%'") > > > > The error is: IndexError: list index out of range > > > > How do I address this problem? > > Use "%%". > > > -- > Jorge Godoy > > "Quidquid latine dictum sit, altum sonatur." > - Qualquer coisa dita em latim soa profundo. > - Anything said in Latin sounds smart. From jcoleman at franciscan.edu Thu Mar 2 15:42:39 2006 From: jcoleman at franciscan.edu (John Coleman) Date: 2 Mar 2006 12:42:39 -0800 Subject: Does '#hash' mean anything in IDLE? In-Reply-To: <1141331534.634181.275880@p10g2000cwp.googlegroups.com> References: <1141331534.634181.275880@p10g2000cwp.googlegroups.com> Message-ID: <1141332159.625375.40540@e56g2000cwe.googlegroups.com> John Coleman wrote: > Greetings, > I am currently trying to learn Python through the excellent > "Learning Python" book. I wrote my first non-trivial program, which > began with several comment lines. One of the comment lines began with > '#hash'. IDLE doesn't colorize it as a comment line but instead colors > the word 'hash' in purple as if it were a key word. Wierd. The behavior > seems easy to trigger: Just open up a new window in IDLE and enter > these two lines: > > #This is a test > #hash should still be a comment line > > Then, after saving, the second line is not colored as a comment line > though the first is. > Is this a bug, or do comment lines which begin with #hash have some > special meaning? > My program ran fine, so it seems that the interpreter itself is > ignoring the line. > > -John Coleman It isn't just #hash, but also things like #dict, #int, #len at the start of a comment line which defeats IDLE's colorization algorithm. Interestingly, things like #while or #for behave as expected so it seems to be built-ins rather than keywords which are the problem. To answer my own question - this is pretty clearly a (harmless) bug. -John Coleman From Chris.Barker at noaa.gov Mon Mar 20 14:39:15 2006 From: Chris.Barker at noaa.gov (Christopher Barker) Date: Mon, 20 Mar 2006 11:39:15 -0800 Subject: Linear regression in NumPy In-Reply-To: References: <1142628938.982098.239850@u72g2000cwu.googlegroups.com> <1142631926.353064.206010@p10g2000cwp.googlegroups.com> <1142639157.977175.257900@u72g2000cwu.googlegroups.com> <%PVSf.52$Qm2.24@trndny03> <1142698211.185324.154130@j33g2000cwa.googlegroups.com> Message-ID: Matt Crema wrote: > > "More generally: Is there any kind of documentation that tells me what > > the functions in NumPy do, and what parameters they expect, how to > > call them, etc. This is a good start too: http://www.tramy.us/guidetoscipy.html Yes, you have to pay for it, but the money goes to the guy who has done a MASSIVE amount of work to get the new numpy out. I would like to see a "Mastering Numpy" book much like the excellent "Mastering Matlab", but some one needs to write it! -Chris From larry.bates at websafe.com Fri Mar 3 17:54:17 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 03 Mar 2006 16:54:17 -0600 Subject: dynamically creating variables In-Reply-To: <1141420408.295582.234290@z34g2000cwc.googlegroups.com> References: <1141420408.295582.234290@z34g2000cwc.googlegroups.com> Message-ID: <4408C919.6090101@websafe.com> rambham at gmail.com wrote: > I am writing a parser and I have a routine that can digest > a series of tokes: > > def digest(*args) > > I use it like this: digest("FOR", "IDENT", "EQ", "INTVAL", "COLON"). > This part works fine. My digest function returns a list of the values > associated with each token. > > dummy1, ident, dummy2, start = digest("FOR", "IDENT", "EQ", "INTVAL", > "COLON") > > But I dont like the way this looks and I want my digest routine to do > more work. I want to be able to specify the variable bindings in the > call to digest - and not have them be on the LHS of the assignment. > > Ideally I want to call digest like this: > > digest("FOR", ("IDENT",ident), "EQ", ("INTVAL",start), "COLON") > > and have ident and start be local variable defined in the place that > calls digest. > > Is it possible to do something like that? > > -Ram > Can't do what you want specifically, but you can stuff everything into a dictionary and pass it around. I'm not 100% sure I understand what you want to accomplish, but I hope this helps. Have digest return a dictionary of tokens/values. tokenDict=digest("FOR", "IDENT", "EQ", "INTVAL", "COLON") then refer to things as tokenDict['ident'], tokenDict['start'] -Larry Bates From jstroud at ucla.edu Fri Mar 10 15:39:09 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 10 Mar 2006 12:39:09 -0800 Subject: read/ edit line from stdin In-Reply-To: References: Message-ID: Clemens Hepper wrote: > Hello, > for my project confux (http://confux.sourceforge.net) I want to read > a line from stdin. > But I don't want the user to type a new line. I want so display a > value which the user can edit. > > For example I want to ask the user for a hostname and I print > "localhost", the user modified it to "localserver" and I read it > after . > > What is the fastest way to realize that? I do NOT want to use curses > (yet) ;-). > > mfg > - eth Why don't you just make "localhost" the default and have the user enter the complete name if they want it different. Seems like this is the way every CL program I've ever seen works. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From per9000 at gmail.com Mon Mar 20 07:03:39 2006 From: per9000 at gmail.com (per9000) Date: 20 Mar 2006 04:03:39 -0800 Subject: Counting number of each item in a list. References: <1142772092.958602.272260@e56g2000cwe.googlegroups.com> <441d58f7$0$13046$626a54ce@news.free.fr> <1142774630.426660.19970@t31g2000cwb.googlegroups.com> <441d6342$1_3@newspeer2.tds.net> <441d9408$0$20430$636a55ce@news.free.fr> <441dab21$0$27059$626a54ce@news.free.fr> Message-ID: <1142856219.734122.299540@i40g2000cwc.googlegroups.com> Dear counters, I have also encountered the above problem, and I frequently use the two blocks of code below. The first one is commented already - except that this version does not start from an empty dict. The second "inverts" the first one. Meaning that a dict in word2hits style: my_dict['the'] = 120 my_dict['word'] = 4 ... my_dict['gene'] = 4 becomes a dict in hits2words style: new_dict[4] = ['word','gene', ...] new_dict[120] = ['the', ...] I used these to count genes in in abstracts from pubmed the when I "invented" them (but it took some time to remove them from the code and use them as functions). def dict_add(indict,inlist,init=1): for item in inlist: if indict.has_key(item): indict[item] += 1 else: indict[item] = init return indict # end def def dict_invert(indict): new_dict = {} for key in indict.keys(): if new_dict.has_key(indict[key]): new_dict[indict[key]].append(key) else: new_dict[indict[key]] = [key] return new_dict #end def A good idea could be to change the header of the first one (if you want the option to start counting from zero) into: def dict_add(inlist,indict={},init=1): /P9K From akameswaran at gmail.com Tue Mar 7 10:09:38 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 7 Mar 2006 07:09:38 -0800 Subject: Difference between a library and a module... In-Reply-To: <1141742982.865424.238550@v46g2000cwv.googlegroups.com> References: <1141742982.865424.238550@v46g2000cwv.googlegroups.com> Message-ID: <1141744178.404390.322750@v46g2000cwv.googlegroups.com> I'm not 100% sure what is a library in python. Your example above is importing a module. Someone else can correct me, but I use libraries to refer to underlying c/c++ code that is required for the python modules to function. So in pure python you are really only dealing with modules. string.replace() I'm 90% sure is a function in the string module. However something like this: foo = "bar" foo.Capitalize() bar.capitalize is executing a method. Actually at this point string.replace() may be a method as well, I don't know for sure as I haven't inspected the string module's code. Read some intro to OOP, for a better understanding, but the main difference between a function and a method, is that a method is associated with some class or object. In Python it's really only objects (even class is an object) Hence when I created the string object foo, and executed Capitalize() it was a method on the string object. the same thing as a function might look something like: # defining a function def capitalize(inStr) #do stuff here to capitalize the string return outStr foo = capitalize("bar") hope this helps. From johnzenger at gmail.com Tue Mar 21 10:48:25 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 21 Mar 2006 07:48:25 -0800 Subject: recursive map on nested list References: <1142942495.517738.86490@v46g2000cwv.googlegroups.com> Message-ID: <1142956105.162241.191110@v46g2000cwv.googlegroups.com> Uglier than yours, but down to two lines: def recur_map(f, data): return [ not hasattr(x, "__iter__") and f(x) or recur_map(f, x) for x in data ] From dimitri.pater at gmail.com Tue Mar 7 14:15:19 2006 From: dimitri.pater at gmail.com (dimitri pater) Date: Tue, 7 Mar 2006 20:15:19 +0100 Subject: New python.org website In-Reply-To: <1141758207.306590.145680@i40g2000cwc.googlegroups.com> References: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> <1141757893.030386.123090@i40g2000cwc.googlegroups.com> <1141758207.306590.145680@i40g2000cwc.googlegroups.com> Message-ID: I do like it, one thing I noticed though: http://www.python.org/doc/ has an image (batteries-included.jpg), a very nice image but it says "new V 1.6". Okay , this may not seem important, but maybe someone (the original artist?) can "update" it. regards, Dimitri On 7 Mar 2006 11:03:27 -0800, projecktzero wrote: > > Oops...it is live. Cool! > > -- > http://mail.python.org/mailman/listinfo/python-list > -- ---- "All truth passes through three stages. First, it is ridiculed. Second, it is violently opposed. Third, it is accepted as being self-evident." ~Arthur Schopenhauer ---- Please visit dimitri's website: www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleaxit at yahoo.com Sat Mar 4 15:17:04 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 4 Mar 2006 12:17:04 -0800 Subject: Easy immutability in python? References: <20060304115259.2e426ca8@samwise.anansi> Message-ID: <1hbocr8.cvkjcct152qaN%aleaxit@yahoo.com> Terry Hancock wrote: ... > I also am not trying to alter the Python language. I am > trying to figure out how to most easily fix __setattr__ etc > to act immutably, *using* the existing features. > > I can already do what I want with some 25-30 lines of code > repeated each time I need it, but I think it's dumb that > it's that complicated. If you need many immutable classes, inject __setattr__ etc into them (via metaclass or otherwise). Alex From jgardner at jonathangardner.net Sat Mar 11 04:39:40 2006 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: 11 Mar 2006 01:39:40 -0800 Subject: Using len() In-Reply-To: <1142065856.986016.181530@j33g2000cwa.googlegroups.com> References: <1142065856.986016.181530@j33g2000cwa.googlegroups.com> Message-ID: <1142069980.020724.175120@j52g2000cwj.googlegroups.com> Methinks you are confused about the structure of your program. If we write the program out in plain English in the form of a recipe, it should look something like this: 1. Get input. 2. Check to see if they guessed right. 3. If not, go back to 1. This structure hints at an infinite loop. The breakout condition is a correct guess. You always need a breakout condition, or the loop goes on forever. (Sometimes you do want an infinite loop. Think about how you would write a web server.) (Note on variable names: "your" and "my" are not clear. Usually, first person ("I", "me", "my") refers to the programmer. The second person ("you", "your") is rarely used. "You" could be the user, the computer, or another programmer. Just use third person ("it", "he", "they"). So, we write an infinite loop in Python: while True: # Get input guess = raw_input() # Is the guess right? if guess == num: # Yep. Break out of the loop. break # Otherwise, loop again. You could put the breaking condition in the "while" line. But since it appears in the middle of the loop, this is difficult to do. So just put it in explicitly in the middle and call it a day. From paul at boddie.org.uk Wed Mar 15 09:56:23 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 15 Mar 2006 06:56:23 -0800 Subject: Tried Ruby (or, "what Python *really* needs" or "perldoc!") References: <1142355126.757569.42160@i40g2000cwc.googlegroups.com> <1142397587.151040.35450@j33g2000cwa.googlegroups.com> <1142434139.499666.281590@v46g2000cwv.googlegroups.com> Message-ID: <1142434583.549275.119100@p10g2000cwp.googlegroups.com> msoulier wrote: > > But, if Python would match Perl for docs available on the command-line, > then I'd have it all at my fingertips. I simply don't understand why > this is not being done. When I'm coding in C, I use the manpages on the > remote host so that I know the docs are correct for my target. Why > can't I do that in Python? What about pydoc? % pydoc os [Clear screen] Help on module os: NAME os - OS routines for Mac, DOS, NT, or Posix depending on what system we're on. FILE /usr/lib/python2.4/os.py MODULE DOCS http://www.python.org/doc/current/lib/module-os.html DESCRIPTION [...] > It's yet another thing that my Perl-using coworkers point out as a Python weakness. In my experience, Perl-using coworkers tend to dredge up all sorts of "weaknesses", although many of them are no more than cheap shots: the name, whitespace, and so on. Sure, Python's documentation system could be better, but let's consider the tools we already have first. Paul From onurb at xiludom.gro Thu Mar 30 04:39:54 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 30 Mar 2006 11:39:54 +0200 Subject: dynamic construction of variables / function names In-Reply-To: <442B95AA.6030905@REMOVEMEcyber.com.au> References: <1143701064.680576.285090@v46g2000cwv.googlegroups.com> <442B95AA.6030905@REMOVEMEcyber.com.au> Message-ID: <442ba7ab$0$14269$626a54ce@news.free.fr> Steven D'Aprano wrote: > Sakcee wrote: > >> python provides a great way of dynamically creating fuctions calls and >> class names from string >> (snip) > Personally, I think the best way is: find another way to solve your > problem. > See Duncan's post for a pretty clean and pythonic solution. Another one that may be more explicit and avoid messing with locals() or globals() is: >> is it correct way, is there a simple way, is this techniqe has a name? > > > I'm told that some people call this "dynamic programming", In some other languages, it could be called 'metaprogramming', but this is such a common idiom in Python that I'd just call this "programming" !-) > but > personally I call it "difficult to maintain, difficult to debug > programming". Oh yes ? Why so ? I've used such patterns hundreds of time, and it has never been a problem so far. Dynamically selecting the function to call given a name (as string) is is a well-known programming pattern. I learned this in C, using a hashtable to store names/function pointer pairs. And that's mostly what the proposed solutions (the one based on globals() or locals() as well as Duncan's class-based one) do - the main difference being that Python offers the hashtable for free !-) nb : I agree that the use of the global or local namespaces may not be the best thing to do - better to use (any variant of) Duncan's solution IMHO. > (Before people get all cranky at me, I'm aware that it isn't *always* > the Wrong Way to solve problems, but it is a technique which is subject > to abuse and can often be avoided by using function objects instead of > function names.) When you get the function name as user input, you cannot directly access the function object. And anyway, what do you think Python do when you call a function ? Python namespaces *are* hash tables mapping symbols names (as string) to objects (as pointers). I don't see much difference here. (nb 2 : I agree that it is of course better to avoid 'manual' namespace lookup whenever possible) -- 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 Mar 20 16:32:29 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 20 Mar 2006 21:32:29 GMT Subject: why isn't Unicode the default encoding? In-Reply-To: References: Message-ID: Robert Kern wrote: > http://www.joelonsoftware.com/articles/Unicode.html That was fascinating. Thank you. So as it turns out, Unicode and UTF-8 are not the same thing? Am I right to say that UTF-8 stores the first 128 Unicode code points in a single byte, and then stores higher code points in however many bytes they may need? If so, I guess I had been mislead by the '8' in the name, thinking that UTF-8 was another way of storing characters in one byte (which would make it no different than Latin-1, I suppose). From siasookhteh at gmail.com Mon Mar 27 18:20:21 2006 From: siasookhteh at gmail.com (Siah) Date: 27 Mar 2006 15:20:21 -0800 Subject: What is Caching my DB In-Reply-To: References: <1143486383.353778.142250@e56g2000cwe.googlegroups.com> Message-ID: <1143501621.415364.233010@i40g2000cwc.googlegroups.com> Helpful Hints Ivan. Thanks for the points. Sia From bdesth.quelquechose at free.quelquepart.fr Sun Mar 5 19:20:47 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 06 Mar 2006 01:20:47 +0100 Subject: django and mod_python In-Reply-To: <1141548927.845787.117860@j33g2000cwa.googlegroups.com> References: <1141548927.845787.117860@j33g2000cwa.googlegroups.com> Message-ID: <440b559a$0$12880$626a54ce@news.free.fr> bapolis at gmail.com a ?crit : > Hi, > > I read the mod_python documentation on the Django site but I'm getting > this error: > > EnvironmentError: Could not import DJANGO_SETTINGS_MODULE > 'accesshiphop.settings' (is it on sys.path?): No module named > accesshiphop.settings > > Here's my httpd.conf: (snip - already answered) BTW, there's a django mailing-list, and IIRC a mod_python mailing-list too. When possible, post to the most specific(s) list(s). From samschul at pacbell.net Sat Mar 4 14:00:26 2006 From: samschul at pacbell.net (sam) Date: 4 Mar 2006 11:00:26 -0800 Subject: The old round off problem? Message-ID: <1141498826.719803.114490@u72g2000cwu.googlegroups.com> Hello all, I am taking a class in scientific programming at the local college. My problem is that the following difference produces round off errors as the value of x increases. For x >= 19 the diference goes to zero.I understand the problem, but am curious as to whether their exists a solution. I have tried various graphing programs,and they all exihibit this problem. thanks in advance Sam Schulenburg f(x) = cosh^2(x) - sinh^2(x) = 1 >>> from math import * >>> for x in range(20): print "x= %2d Sinh^2(x) = %20.3f f(x) = %2.10f "%(x,pow(cosh(x),2),pow(cosh(x),2)- pow(sinh(x),2)) x= 0 Sinh^2(x) = 1.000 f(x) = 1.0000000000 x= 1 Sinh^2(x) = 2.381 f(x) = 1.0000000000 x= 2 Sinh^2(x) = 14.154 f(x) = 1.0000000000 x= 3 Sinh^2(x) = 101.358 f(x) = 1.0000000000 x= 4 Sinh^2(x) = 745.740 f(x) = 1.0000000000 x= 5 Sinh^2(x) = 5507.116 f(x) = 1.0000000000 x= 6 Sinh^2(x) = 40689.198 f(x) = 1.0000000000 x= 7 Sinh^2(x) = 300651.571 f(x) = 0.9999999999 x= 8 Sinh^2(x) = 2221528.130 f(x) = 1.0000000000 x= 9 Sinh^2(x) = 16414992.784 f(x) = 1.0000000037 x= 10 Sinh^2(x) = 121291299.352 f(x) = 1.0000000298 x= 11 Sinh^2(x) = 896228212.033 f(x) = 0.9999998808 x= 12 Sinh^2(x) = 6622280532.961 f(x) = 1.0000019073 x= 13 Sinh^2(x) = 48932402357.710 f(x) = 0.9999923706 x= 14 Sinh^2(x) = 361564266073.369 f(x) = 0.9999389648 x= 15 Sinh^2(x) = 2671618645381.616 f(x) = 1.0000000000 x= 16 Sinh^2(x) = 19740740045670.668 f(x) = 0.9921875000 x= 17 Sinh^2(x) = 145865435631864.219 f(x) = 1.0000000000 x= 18 Sinh^2(x) = 1077807886778799.250 f(x) = 1.0000000000 x= 19 Sinh^2(x) = 7963982939278438.000 f(x) = 0.0000000000 >>> From joel.hedlund at gmail.com Fri Mar 10 07:47:24 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Fri, 10 Mar 2006 13:47:24 +0100 Subject: A bit OT: Python prompts display as nested mail quotes in Thunderbird In-Reply-To: References: Message-ID: > Do you have the Quote Colors extension? I do now. :-) > You can also disable the use of colors in the options, but that will > remove the colors for all messages. Or I can tell it to display colored '>' chars. Marvellous! Thanks for the advice! You're a real help. /Joel Hedlund From aisaac0 at verizon.net Thu Mar 23 23:34:32 2006 From: aisaac0 at verizon.net (David Isaac) Date: Fri, 24 Mar 2006 04:34:32 GMT Subject: __slots__ References: <1143106365.996810.269780@z34g2000cwc.googlegroups.com> Message-ID: "Ziga Seilnacht" wrote: > If you want to restrict attribute asignment, you should use the > __setattr__ special method, see: > http://docs.python.org/ref/attribute-access.html That "should" is what I am asking about. If I understand, in the simplest case, you want me to say something like def __setattr__(self,name,value): if name in myattrlist: object.__setattr__(self,name,value) else: raise AttributeError instead just saying __slots__ = myattrlist I understand that this *is* the prevailing advice. But why? > >>> class A(object): > ... pass > ... > >>> class B(A): > ... __slots__ = ('spam',) > ... > >>> b = B() > >>> b.eggs = 1 > >>> b.eggs > 1 A good example of something that could be easily missed, and possibly an answer to my question above. (Although not I think if I am subclassing object.) Thanks, Alan Isaac From jordan.taylor2 at gmail.com Sat Mar 25 20:51:30 2006 From: jordan.taylor2 at gmail.com (jordan.taylor2 at gmail.com) Date: 25 Mar 2006 17:51:30 -0800 Subject: noobie mkdir problem/question In-Reply-To: <1143332293.822910.17680@v46g2000cwv.googlegroups.com> References: <1143322904.618585.188740@t31g2000cwb.googlegroups.com> <1143330785.575857.201110@u72g2000cwu.googlegroups.com> <1143332293.822910.17680@v46g2000cwv.googlegroups.com> Message-ID: <1143337890.880552.185910@j33g2000cwa.googlegroups.com> First, what version of python are you using? 2.4.2 (and some previous versions) use file() instead of open(), although open may still work. also, if your code in the previous post is still using: outputFname = given + '.log' outputFile = open(os.path.join(xrefs,outputFname), 'w') I hope you have 'given' defined somewhere, since it's not in the code you show. give this a try: output = file(xrefs + r'\filenamewhatever', 'w') output.write(data) output.close() From lory88 at gmail.com Mon Mar 6 20:19:20 2006 From: lory88 at gmail.com (lory88 at gmail.com) Date: 6 Mar 2006 17:19:20 -0800 Subject: Help - just a few lines of code needed Message-ID: <1141694360.291846.153820@v46g2000cwv.googlegroups.com> Hi I hope someone can help me out with a very SIMPLE program about whole string permutations. That is: given a list of strings, the required outcome is a complete set of all their possible permutations. It's like character permutations of a string, but this time it is whole strings instead of single characters that have to be permuted. I need this because I don't remember exactly the password to open my zipped archives, but i do remember the bits of strings that made up the long passphrase. Could someone kindly write a simple program that, after reading a set of strings contained in a .txt file (one string on each line), produces as output another .txt file containing all the possible permutations/combinations of those strings. For example, the text file with the set of strings may contain: HOUSE jolly --- 0& 99 and the output file contains: HOUSE HOUSEjolly HOUSE--- HOUSE0& and so on... ...with the word combinations growing extensively, so as to exhaust all the possibilities: e.g. ---99jolly0& jolly0&---99HOUSE etc. etc. Unfortunately I am not able to program it myself, so I would appreciate if someone could write this piece of software, compile it (for DOS or Windows) and send the .exe file to: lory88 at gmail . com I thank you all in advance. Lory From fairwinds at eastlink.ca Wed Mar 1 23:11:51 2006 From: fairwinds at eastlink.ca (David Pratt) Date: Thu, 02 Mar 2006 00:11:51 -0400 Subject: WxPython question re: embedded activex internet explorer and excel In-Reply-To: <1141270626.223055.158510@u72g2000cwu.googlegroups.com> References: <1141270626.223055.158510@u72g2000cwu.googlegroups.com> Message-ID: <44067087.9070900@eastlink.ca> Hi jojoba. I work with wxPython too but cannot answer this question. There is an active and friendly community of wxPython users on wxPython-users at lists.wxwidgets.org Robin Dunn, the lead person behind wxPython and others provide excellent advice and support on this list. Regards, David jojoba wrote: > Hi > I currently am using an activex wrapper in wxpython to embed Internet > Explorer in a wxPanel: > > IEmodule=win32com.client.gencache.EnsureModule('{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}', > 0,1,1) > InternetExplorerActiveXClass = MakeActiveXClass(IEmodule.WebBrowser, > eventObj = self) > self.WebBrowser = InternetExplorerActiveXClass(self, > -1) > > (where self is a wx.Panel) > > That was ok. > However, I am creating multiple of these activex webbrowsers and > putting them in a wx.Notebook, one per page (where each page is a > wx.Panel). > On each page, i load a different .xls excel file: > > self.WebBrowser.Navigate2(excelFilePath) > > Great. All the files load fine. > Ok, here's the weird part. > When i choose among the different tabs for the wx.Notebook, I can see > all the excel files fine. I can go into each and edit them too. But for > some reason, i can't get focus away from the last-loaded excel file. > That is, I can really only see the cursor flashing in a worksheet excel > if and only if i am in the last-loaded excel file. > > I tried self.WebBrowser.Document.Application.Workbooks[0].Activate() to > activate another workbook (representing a different .xls file) but i > get a win32com error saying the "Workbook Activate method failed" > > Is there any way for me to get out of this? Does anyone have any idea > how to bring other workbooks into focus using this activex scheme? Or > am i approaching this from the completely wrong angle? > > thanks to anyone who can get past this madness, > jojoba > From cito at online.de Tue Mar 21 18:09:48 2006 From: cito at online.de (Christoph Zwerschke) Date: Wed, 22 Mar 2006 00:09:48 +0100 Subject: Console UI library for Python In-Reply-To: References: Message-ID: Sean Hammond schrieb: > > Anyone know of a good library for building text-mode user-interfaces in > Python, like if I wanted to make an email program like Pine or Mutt? > > A quick Google reveals Urwid: > > http://excess.org/urwid/ > > which looks pretty good. Urwid is probably a more sophisticated solution, but for very simple applications, you may also consider http://sourceforge.net/projects/pythondialog -- Christoph From ethrandil at gmx.net Sun Mar 26 20:27:13 2006 From: ethrandil at gmx.net (Clemens Hepper) Date: Mon, 27 Mar 2006 03:27:13 +0200 Subject: Bitwise OR? In-Reply-To: References: <1143187977.384459.225840@i40g2000cwc.googlegroups.com> <1143190128.783253.62430@i40g2000cwc.googlegroups.com> Message-ID: Okay... pythons build-in methods are quite fast. so is hex(). with about 64 kb memory i can write it with a 16 bit dictionary where the dictionary generation itself is not yet optimized: def genBitList(exp): next = lambda now: [x+'0' for x in now]+[x+'1' for x in now] result = [""] for x in range(exp): result = next(result) return result _digits = genBitList(16) def bitstring2(number): """lsb------>msb""" rlist = list() if number >= 0: while number: rlist.append( _digits[number & 0xFFFF] ) number >>= 16 return ''.join(rlist).rstrip('0') else: while number != -1: rlist.append( _digits[number & 0xFFFF] ) number >>= 16 return ''.join(rlist).rstrip('1') this is quite fast and in lots of cases faster than the hex()-version. however your method (with my inverses formatting) is very fast, too and without so much memory expense: _nibbles = {"0":"0000", "1":"0001", "2":"0010", "3":"0011", "4":"0100", "5":"0101", "6":"0110", "7":"0111", "8":"1000", "9":"1001", "a":"1010", "b":"1011", "c":"1100", "d":"1101", "e":"1110", "f":"1111", "l":"", "-":"", "x":""} from string import maketrans, translate _invert = maketrans('01', '10') def bitstring3( number ): if number > 0: return ''.join( [_nibbles[d] for d in hex( number ).lower()] ).lstrip( '0' ) else: return translate(''.join( [_nibbles[d] for d in hex( ~number ).lower()] ).lstrip( '0' ), _invert) Benchmark: for 0xa: bitstring2: 0.61802315712 bitstring3: 0.91001200676 for 0xaaaa: bitstring2: 0.561501026154 bitstring3: 1.11787199974 for 0xaaaaaaaaaaaa: bitstring2: 1.2295820713 bitstring3: 1.61559510231 for 0xaaaaaaaaaaaaaaaaaaaaaaaa: bitstring2: 1.90036797523 bitstring3: 2.2683339119 for -0xaaaaaaaaaaaaaaaaaaaaaaaa: bitstring2: 2.81339716911 bitstring3: 2.74266886711 mfg - eth From caseyhHAMMER_TIME at istar.ca Thu Mar 23 23:31:48 2006 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Fri, 24 Mar 2006 04:31:48 GMT Subject: New development windows, IronPython or PythonWin References: <1143135013.513865.103820@u72g2000cwu.googlegroups.com> <1143166004.664604.207250@j33g2000cwa.googlegroups.com> Message-ID: Butternut squash wrote: >sanxiyn at gmail.com wrote: > >> IronPython is currently nowhere near production quality. I would not >> recommend it. > >But it's so cool. It's cool to have bugs? That really BUGS ME! -- Regards, Casey From sjmachin at lexicon.net Mon Mar 20 06:17:28 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 20 Mar 2006 22:17:28 +1100 Subject: ANNOUNCE: xlrd 0.5.2 -- extract data from Excel spreadsheets In-Reply-To: <1142852445.087922.250140@g10g2000cwb.googlegroups.com> References: <441c7714$1_2@newspeer2.tds.net> <441C9F4D.1030203@lexicon.net> <441ccb61$1_3@newspeer2.tds.net> <441D23F2.7090808@lexicon.net> <1142850490.058912.138560@e56g2000cwe.googlegroups.com> <441E865D.20508@lexicon.net> <1142852445.087922.250140@g10g2000cwb.googlegroups.com> Message-ID: <441E8F48.6070404@lexicon.net> On 20/03/2006 10:00 PM, jcmendez wrote: > Hi John > > I'd like to create a dependency graph and plot it with Graphviz. I've > played a bit with exporting the sheet in XML format, and parsing the > XML. That somehow works, but it would be much better if the users > wouldn't need to save as the sheets, just put them is a shared > directory where I can get them with the script. > > Thanks!! > I guess that you need, for each formula cell in a worksheet, a list of the cells that are referred to by the formula ... is that correct? From aleaxit at yahoo.com Tue Mar 21 11:45:18 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 21 Mar 2006 08:45:18 -0800 Subject: user-supplied locals dict for function execution? References: <1142875454.906993.126370@v46g2000cwv.googlegroups.com> <441eedbd$0$20865$636a55ce@news.free.fr> <1142879594.924929.96440@v46g2000cwv.googlegroups.com> <441f0623$0$23127$626a54ce@news.free.fr> <1142887575.402624.156050@e56g2000cwe.googlegroups.com> Message-ID: <1hcjk7w.qllhsrblulyN%aleaxit@yahoo.com> Lonnie Princehouse wrote: ... > @namespace # indicates function should be executed in namespace > def initialize_namespace(): > x = 5 > > # versus the alternative > > __namespace__ = { > 'x' : 5, > } Hm, what about: ns = namespace(x=5) and perhaps later ns.update(y=6) if you need to add a name to ns? You can start with 'namespace=dict' (in whatever ubernamespace you'd define your @namespace decorator above) and change it later in any way you wish -- and it's vastly less blackmagical, too. Alex From sybrenUSE at YOURthirdtower.com.imagination Thu Mar 2 11:48:43 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 2 Mar 2006 17:48:43 +0100 Subject: white space in expressions and argument lists References: Message-ID: John Salerno enlightened us with: > Guido listed a few rules that he'd like to see implemented in 2.5, > and one of them was no more than one consecutive white space. I > don't know how realistic some of those suggestions are, but they > seem to be getting a little to restrictive. I just read the PEP where my way of alignment is under a 'NO' header. Too bad, since I think it can make things a lot clearer. 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 PPNTWIMBXFFC at spammotel.com Tue Mar 21 14:42:56 2006 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Tue, 21 Mar 2006 20:42:56 +0100 Subject: From Python to c++ Message-ID: This is actually a c++ problem. Got no satisfying answer on comp.lang.c++. Maybe you can help better because I know, there are many c++-converts ;). Suppose you've got the following list (first line has field names, second line has types and any row after is data): csv = "name,age,place\nstring,int,string\nMac,25,Zurich\nMike,55,Oslo" and you would like to turn it into a dictionary: parsed = { "name":["Mac", "Mike"], "age":[25, 55], "place":["Zurich", "Oslo"] } A trivial task in Python. In C++ it is cumbersome. I was thinking to put the parsed data into a map: map > I have no problem with the key (string) but the value (vector) needs to be of varying type. I think C++-STL does not allow what I want. The following proposal is useless: [...] A simple solution, make two maps: std::map > result_name; std::map > result_age; [...] I want to build the map of lists dynamically - it can have many fields or just one... and I would like to have simple interface (as Python offers). - I cannot import python into the c++ environment (Borland Developer 2006) and I know no one who was able to. - I cannot write (*sigh*) the app in Python. Any suggestions are very welcome! Regards, Marco (Forced to code in c++ again let me estimate the simplicity of python) From spamspam at spam.eggs Tue Mar 14 14:01:07 2006 From: spamspam at spam.eggs (Ben C) Date: 14 Mar 2006 19:01:07 GMT Subject: calling another python file within python References: Message-ID: On 2006-03-14, Kevin wrote: > i have a python file called pyq which outputs stock quotes, currently i > also have a html file that takes stock ticker inputs, i would like to > bridge the two by building another program that takes the html inputs > and uses them to call the pyq stock ticker program and then output them > into a text file... > > any idea how to do this? my tentative code is: > > > > #!/usr/bin/python > > import os > import urllib > os.system("python pyq.py ibm > text1.txt") Rather than invoke the shell (which is what system does), you can just do it all from Python. Something like: import pyq pyq.run("ibm") Then in pyq.py, you could have something like this: def run(filename): # do whatever... def main(): # check args etc.. run(sys.argv[1]) if __name__ == "__main__": main() This way pyq would work from the shell if you wanted to run it that way, and also as a module. Not quite sure of the details of the input. If the other program is creating this file ibm which you're immediately reading as soon as it appears you'd probably be better off with a pipe. See Python docs for the "socket" module. Or less portably and if you're on a UNIX system you could use a named pipe (created with mkfifo). > note: currently the text1.txt outputted is just blank, however if i > run the command normally as 'python pyq.py ibm' in the command line, > it works correctly and gives me the price of ibm. If you launch pyq.py like this it has to be in the current working directory of the other program. If you just go os.system("pyq.py ibm") and pyq.py has the #! business at the start of it, then pyq.py has to be in your PATH. Otherwise it should work. So long as you're sure the file ibm has been created by this point. One of the benefits of doing it with import instead (the thing I described above) is you don't have to worry about the shell and its environment, or what PATH is, but only the Python environment (PYTHONPATH, sys.path, that kind of thing). It's more portable. From no-spam at no-spam-no-spam.com Sat Mar 11 18:55:21 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sun, 12 Mar 2006 00:55:21 +0100 Subject: "RuntimeError: dictionary changed size during iteration" ; Good atomic copy operations? In-Reply-To: References: <104lhpbuofu4l.jz32d3oa1uk7$.dlg@40tude.net> Message-ID: Tim Peters wrote: > [robert] > >>... >>PS: how does ZODB work with this kind of problem? I thought is uses cPickle? > > > It does. Each thread in a ZODB application typically uses its own > connection to a database. As a result, each thread gets its own > consistent view of database objects, which can (and routinely does) > vary across threads. No app-level synchronization is necessary > because no sharing of in-memory objects occurs. When N threads each > load a single persistent object from its own connection, N distinct > in-memory revisions of that object are created (one per connection == > one per thread). If more than one thread modifies the same persistent > object, the first thread to commit its changes "wins", and later > threads that try to commit changes to the same object may suffer a > ConflictError exception at commit time. Between transaction > boundaries, each thread has an independent view of database state. > Pragmatically, it's much more like programming with multiple processes > than with multiple threads. Thanks for that details. So when committing objects with multithreaded changes on a complex object into ZODB, it would raise the same a RuntimeError on altered dicts/lists... --- Looked up copy.py meanwhile: copy and deepcopy use : def _copy_dict(x): return x.copy() d[types.DictionaryType] = _copy_dict .... def _deepcopy_dict(x, memo): y = {} memo[id(x)] = y for key, value in x.iteritems(): y[deepcopy(key, memo)] = deepcopy(value, memo) return y d[types.DictionaryType] = _deepcopy_dict Thus deepcopy (but not copy) seems to also expose itself to this RuntimeError as .iteritems() will iterate on the original dict! ( Would be maybe better to use x.items() here - as it was maybe before py2.2 ) Its the same Problem as with cPickle.dump. Thus there seems to be no RuntimeError-save possibility in the standard Python lib to get a "current view" of an object tree in threaded applications. Guess it would be more wise to not expose deepcopy, cPickle.dump etc. to this kind of RuntimeError unnecessarily. The speed gain of the iterator-method - if any - is minor, compared to the app crash problems, which are not easy to discover and work-around (because they happen rarely on fast computers). Robert From mfranklin1 at gatwick.westerngeco.slb.com Mon Mar 6 05:04:38 2006 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 06 Mar 2006 10:04:38 +0000 Subject: Tix Note Book In-Reply-To: <1141625274.483448.37600@v46g2000cwv.googlegroups.com> References: <1141625274.483448.37600@v46g2000cwv.googlegroups.com> Message-ID: <440C0936.3090608@gatwick.westerngeco.slb.com> anil.pundoor at gmail.com wrote: > hi > > am using Tix notebook and i have two frames in that. am adding some > widgets in to both of the frames. now i want to delete all of the > widgets in one of the frame. i dont want to delete the frame, but its > childres. > so how can i get the sub widgets within that frame. > > Thanks in advance > Anil > Anil, Standard Tkinter widgets have a .children so for your frame widget try printing the value of yourframe.children like so:- Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> import Tkinter >>> root=Tkinter.Tk() >>> l=Tkinter.Label(root) >>> l.pack() >>> print root.children {'10703960': } >>> HTH Martin From wuwei23 at gmail.com Tue Mar 28 02:02:09 2006 From: wuwei23 at gmail.com (alex23) Date: 27 Mar 2006 23:02:09 -0800 Subject: Difference between 'is' and '==' References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <4427d287$0$38669$edfadb0f@dread12.news.tele.dk> Message-ID: <1143529328.964467.132610@t31g2000cwb.googlegroups.com> Felipe Almeida Lessa wrote: > I said [constants defined in your code] can (maybe "should"?) be used with "is", and > AFAICT I'm right as well: > >>> b = a > >>> b is a > True You should _never_ use 'is' to check for equivalence of value. Yes, due to the implementation of CPython the behaviour you quote above does occur, but it doesn't mean quite what you seem to think it does. Try this: >>> UPPERLIMIT = 100 >>> i = 0 >>> while not (i is UPPERLIMIT): >>> i+=1 >>> print i Comparing a changing variable to a pre-defined constant seems a lot more general a use case than sequential binding & comparison...and as this should show, 'is' does _not_ catch these cases. - alex23 From grante at visi.com Tue Mar 7 17:31:38 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 07 Mar 2006 22:31:38 -0000 Subject: Any advantage in LISPs having simpler grammars than Python? References: <1141770067.041526.292360@p10g2000cwp.googlegroups.com> Message-ID: <120s2eag21k9571@corp.supernews.com> On 2006-03-07, seberino at spawar.navy.mil wrote: > Is there any advantage to a language having a nice mathematically > compact grammar like LISP does? (or at least used to?) Yes. Grammars like LISP's make it easy for programs to generate and read code. Grammars like Python's make it easy for humans to generate and read code. > Many have admired the mathematically simple grammar of LISP > in which much of the language is built up from conses IIRC. > > Python's grammar seems complicated by comparison. People are pretty good at complicated grammars if they're well designed (people seem to like grammars with a fair bit of redundancy), and can be amazingly bad at simple grammars. > Is this anything to worry about? That depends. Are you a computer program or a person? If the former, LISP is definitely for you. If the latter, then I'd recommend Python. (And I used to write real-world apps in Scheme before I discovered Python). -- Grant Edwards grante Yow! I think my CAREER at is RUINED!! visi.com From Ido.Yehieli at gmail.com Fri Mar 17 09:04:00 2006 From: Ido.Yehieli at gmail.com (Ido Yehieli) Date: 17 Mar 2006 06:04:00 -0800 Subject: Python / glade fundamentals In-Reply-To: References: Message-ID: <1142604240.110403.110560@v46g2000cwv.googlegroups.com> Hi Doug, maybe you will find it easyer to use GladeGen to generate the skeleton of your application rather then coding it yourself. Take a look here: http://www.linuxjournal.com/article/7421 Cheers, Ido Yehieli From deets at nospam.web.de Sat Mar 18 13:44:30 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 18 Mar 2006 19:44:30 +0100 Subject: insert chars into string In-Reply-To: <1142645536.492888.216530@g10g2000cwb.googlegroups.com> References: <1142645536.492888.216530@g10g2000cwb.googlegroups.com> Message-ID: <4832oeFi5gipU1@uni-berlin.de> eight02645999 at yahoo.com schrieb: > hi > is there a string method to insert characters into a string? > eg > str = "abcdef" > i want to insert "#" into str so that it appears "abc#def" > > currently what i did is convert it to a list, insert the character > using insert() and then join them back as string.. If you are frequently want to modify a string in such a way, that this is the recommended way to do so. It might be that there are mutable-string implementations out there that make that easier for you - but in the end, it boils down to using list, so that the overhead of concatenating strings is encountered only once, on the end when you actually need the result. Diez From cowie.rob at gmail.com Thu Mar 16 04:41:43 2006 From: cowie.rob at gmail.com (Rob Cowie) Date: 16 Mar 2006 01:41:43 -0800 Subject: Installing PySQLite on OS X 10.4 In-Reply-To: References: <1142427211.939368.153850@z34g2000cwc.googlegroups.com> <1142432155.902702.220070@j33g2000cwa.googlegroups.com> <1142437697.702026.47330@j52g2000cwj.googlegroups.com> Message-ID: <1142502103.152888.156670@z34g2000cwc.googlegroups.com> Cheers. I should have read the installation notes more carefully :) Rob C From fred at adventistcare.org Wed Mar 22 20:58:11 2006 From: fred at adventistcare.org (Sells, Fred) Date: Wed, 22 Mar 2006 20:58:11 -0500 Subject: need SOAPpy help Message-ID: <1A4BF05172023E468CB6E867923BC904109683@accmail2.sunbelt.org> I've just been asked to do a soap client for some vendor software. I'm able to load the WSDL and discover the methods, but when I go to call a method it doesn't see it. I should be passing in a string that is named "testValue" I've been working from the soap demoes with soappy 0.12.0. I've found so much via google that I don't know where to start or what matches this version of soappy and what is based on older releases. I would appreciate some links or code snippets that illustrate using soap 0.12.0. I apologize for not including my code, but I'm on a different computer tonight. --------------------------------------------------------------------------- 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 singletoned at gmail.com Wed Mar 29 10:52:41 2006 From: singletoned at gmail.com (Ed Singleton) Date: Wed, 29 Mar 2006 16:52:41 +0100 Subject: Doc suggestions (was: Why "class exceptions" are not deprecated?) In-Reply-To: References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com> <1143070060.384366.25480@z34g2000cwc.googlegroups.com> <1143574346.354680.136060@i39g2000cwa.googlegroups.com> <34bb7f5b0603290047o21b9a1b7k64cdd206f604fc10@mail.gmail.com> Message-ID: <34bb7f5b0603290752p48a1b818x4570d189153cbcdc@mail.gmail.com> On 29/03/06, Fredrik Lundh wrote: > > btw, one alternative could be to use an infogame site for this purpose: > > > > http://infogami.com > > > > this gives you revision history, a permissions system (limiting editing to > > registered users might be a good idea), comments, an associated blog, > > voting, feeds, change logs, etc. > > alright, I got bored and uploaded a copy of the current Python tutorial to > > http://pytut.infogami.com Damn. You beat me to it by an hour. http://singletoned.infogami.com/_special/index I had a nightmare with character encodings (mainly because I'm terrible with them). I have a script written that does it all for me, but it keeps choking on characters. I just tried randomly converting things to Unicode at various points for over an hour until it worked. Ed From aleaxit at yahoo.com Thu Mar 16 10:33:18 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Mar 2006 07:33:18 -0800 Subject: bisect and Queue modules in Python 2.4 References: Message-ID: <1hca7kz.ktr0ns19p4obxN%aleaxit@yahoo.com> Peter Otten <__peter__ at web.de> wrote: > SA Trygubenko wrote: > > > q.queue used to be a list, and now it is something else? > > > > I was using bisect module to implement min priority queue, as described > > in python library reference (see > > http://www.python.org/doc/2.3.5/lib/bisect-example.html). I have found > > out that in Python 2.4 q.queue does not support "insert" anymore, which > > breaks bisect. Please help! > > class PriorityQueue(Queue.Queue): > def _put(self, item): > bisect.insort(self.queue, item) > def _init(self, maxsize): > self.maxsize = maxsize > self.queue = [] > def _get(self): > return self.queue.pop(0) > > or somesuch might work. Yep, it should, but using heapq instead of bisect is, I suspect, way better -- there's a recipe on the Cookbook for that (Queue+heapq), and though I (of course;-) prefer the version as edited for the printed (2nd) edition, the online one can also no doubt be useful. Alex From ckapop at comcast.net Mon Mar 6 14:36:30 2006 From: ckapop at comcast.net (Chuck) Date: 6 Mar 2006 11:36:30 -0800 Subject: Compile ui files from within Eclipse Message-ID: <1141673790.419486.324760@v46g2000cwv.googlegroups.com> Hello, I am new to the Eclipse IDE. I am using pydev plug-in to create python projects. Is there a way to create custom builders to build certain types of files? I have done this with other IDE's but can't seem to figure it out with Eclipse. I am trying to build *.ui files of a pydev project to create the corresponding py files. For example to do this the manual way I would: pyuic.exe c:\source.ui > c:\dest.py Thanks. From godoy at ieee.org Thu Mar 9 11:17:47 2006 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 09 Mar 2006 13:17:47 -0300 Subject: Inline assignments References: <1141918168.673024.145610@z34g2000cwc.googlegroups.com> Message-ID: <87ek1bh9sk.fsf@ieee.org> Duncan Booth writes: > wrote: > >> Coming from a background that exposed me to far too many languages, I >> find the latter two examples (i.e. use try/except) to be horrible >> solutions. It's not a matter of light/heavy weight, it's a matter of >> using exceptions for normal loop flow control is a really bad idea. >> 1) I think it's less clear why the loop works >> 2) The possibility (in more complicated examples) that this could mask >> a real exception (if for example, your function > > I'm waiting for the end of that sentence... While in the loop to mount the list, there was an exception thrown. I mean raised. :-) ;-) -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From steve at hastings.org Wed Mar 29 13:49:24 2006 From: steve at hastings.org (Steve R. Hastings) Date: Wed, 29 Mar 2006 10:49:24 -0800 Subject: any() and all() on empty list? References: <1143622860.716668.231370@v46g2000cwv.googlegroups.com> Message-ID: On Wed, 29 Mar 2006 21:34:08 +1000, Steven D'Aprano wrote: > While the implemented behaviour might be more practical than the > alternatives, it is still worrying paradoxical. If "All sheep are woolly", > then obviously it must also be true that "Any sheep is woolly". More > formally, if all(X), then any(X) -- except for the case of empty X. Hmmm. It seems strange, but Tim Peters explained it well. It would also seem strange if this didn't work: all(lst0) and all(lst1) == all(lst0 + lst1) Clearly that should work, and it shouldn't fail just because one of the lists happens to be empty. If you are working with a list, you can just do this: lst and all(lst) What bothers me is the iterator case. There is no simple way to write a test like the above if you have an iterator. Hmmm. How about this? def truecount(seq): count_true = 0 count= 0 for x in seq: if x: count_true += 1 count += 1 return count_true, count count_true, count = truecount(enough_evidence(x) for x in suspected_attacks) if not count: print "Walk free!" elif count == count_true: print "Send him to Gitmo!" else: print "%d proven attacks out of %d suspected" % (count_true, count) if float(count_true) / float(count) >= 0.8: print "preponderance of evidence!" The good thing is that these are simple functions that you can write for yourself. I'm happy any() and all() will be built in, but I don't know that there is sufficient need for truecount() or anything similar. If you need it, just write it. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From stefan.behnel-n05pAM at web.de Tue Mar 14 02:43:47 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 14 Mar 2006 08:43:47 +0100 Subject: markov query In-Reply-To: <1142309974.440477.192600@u72g2000cwu.googlegroups.com> References: <1142309974.440477.192600@u72g2000cwu.googlegroups.com> Message-ID: <44166d7d$0$12231$9b4e6d93@newsread2.arcor-online.net> Don't know of a Python module (although this doesn't look complex enough for a package anyway...), but kpp9c wrote: > P.S. Does any one know first of all whether these are called markov > tables, transition tables or probability tables? I am not sure i am > referring to this correctly and what the differences would be if any as for terminology: http://www.csse.monash.edu.au/~lloyd/tildeMML/Structured/HMM.html http://en.wikipedia.org/wiki/Hidden_Markov_model Hope it helps, Stefan From reply.in.the.newsgroup at my.address.is.invalid Wed Mar 29 14:14:36 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 29 Mar 2006 21:14:36 +0200 Subject: instance and class-hierarchy ? References: <4901irFm4cgvU1@individual.net> Message-ID: Bror Johansson: >I have a class-hierarchy (fairly deep and fairly wide). > >Is there a good and general way to test an instance-object obj for having a >class belonging to a certain "sub-tree" of the hierarchy with a common >parent class C? isinstance(obj,C) -- Ren? Pijlman From keith.b.perry at gmail.com Thu Mar 23 09:22:14 2006 From: keith.b.perry at gmail.com (kbperry) Date: 23 Mar 2006 06:22:14 -0800 Subject: Convert Word .doc to Acrobat .pdf files Message-ID: <1143123734.158567.97310@i39g2000cwa.googlegroups.com> Hi all, Background: I need some help. I am trying to streamline a process for one of our technical writers. He is using Perforce (version control system), and is constantly changing his word documents, and then converts them to both .pdf and "Web page" format (to publish to the web). He has a licensed copy of Adobe Acrobat Professional (7.x). Questions: Does Acrobat Pro, have some way to interface with it command-line (I tried searching, but couldn't find anything)? Is there any other good way to script word to pdf conversion? Note: The word documents do contain images, and lots of stuff besides just text. From sullivanz.pku at gmail.com Thu Mar 2 20:53:38 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 2 Mar 2006 17:53:38 -0800 Subject: Making a tiny script language using python: I need a string processing lib Message-ID: <1141350818.374837.197270@v46g2000cwv.googlegroups.com> I do not know if there is any lib specially designed to process the strings in scipt language. for example: I hope to process the string"print a,b,c,d,e "in the form"command argumentlist" and return: {'command'='print', 'argumentlist'=['a','b','c','d','e']} Are there any lib to implement this? Ideally , the lib should have a function like below: def extract(commandstring, splitformat) eg: extract("see#you at tonight","what#whom at when") return: {"what":"see","whom":"you","when":"tonight"} extract("1;2;3;4;5","list[;]") return: {"list":['1','2','3','4','5']} extract("print a,b,c,d,e","command arglist[,]") return: {"command":"print","arglist":['a','b','c','d','e']} extract("fruit:apple~orgrange~pear~grape#name:tom;sam;dim;ham" ,"class1:instance1[~]#class2:instance2[;]") return: {"class1":"fruit", instance1:['apple','orange','pear','grape'], "class2":"name", "instance2":['tom','sam','dim','ham'] } ####### # # # # # # # # # # # # # # # ####### # # # # # # # # # # # # # # # # From steve at REMOVETHIScyber.com.au Wed Mar 8 06:29:29 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 08 Mar 2006 22:29:29 +1100 Subject: Simple questions on use of objects (probably faq) References: Message-ID: On Wed, 08 Mar 2006 11:00:09 +0000, Matt Hammond wrote: >> 4: Can I avoid the dummy counter i in the for loop and do something >> like: >> yz=[y[:-1].x-y[1:].x] > > yz = [e.x for e in y] > yz.reverse() I don't think that's what the O.P. actually wants. He seems to have misused slicing syntax as some sort of weird replacement for a for loop. Of course, I could be wrong. -- Steven. From tim.golden at viacom-outdoor.co.uk Thu Mar 2 07:56:01 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 2 Mar 2006 12:56:01 -0000 Subject: why? [win32com/WMI] Message-ID: <9A28C052FF32734DACB0A288A3533991044D25D9@vogbs009.gb.vo.local> [Sergey] | "Tim Golden" wrote in | message news:mailman.2569.1141231029.27775.python-list at python.org... | [Sergey] | | >import wmi | >c = wmi.WMI (computer="srv", user="Admin at zzz.ru", password="****") | >pid, retval = c.Win32_Process.Create (CommandLine="notepad.exe") | | Wonderful... It works. Also, in case you haven't, have a look at the cookbook page: http://timgolden.me.uk/python/wmi_cookbook.html which has several useful examples. 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 rice.jeffrey at gmail.com Thu Mar 16 22:58:36 2006 From: rice.jeffrey at gmail.com (J Rice) Date: 16 Mar 2006 19:58:36 -0800 Subject: Threads modify "global" variable -- asking for trouble? Message-ID: <1142567916.313302.109920@i39g2000cwa.googlegroups.com> I have been experimenting with some thread programming, but as I'm doing this on my own I am worried I might be making a major mistake. Here's a brief rundown of what I am working on. Multiple threads, via Queue, are used to perform RBL checks on an IP. The threads are passed a defined class (ConnectionScore) in their init. This is used to collect the results, including a method to add the result. If I run the program, everything goes fine and once all the threads complete the main program has all the data from their RBL checks in the ConnectionScore class. It seems to work, even with an obscene (and silly) number of WORKERS and RBLs to check. But I was reading in the Python Cookbook this evening and it raised the issue in my mind of what happens if multiple threads try to add data to the class at the same time. I've attached the code below. The ConnectionClass.addRBL method just takes the result and adds it to a dictionary object attached to the class. #!/usr/bin/python from UCE_weight import ConnectionScore from rbl import * import Queue import threading import time, random starttime = time.time() WORKERS=5 class Worker(threading.Thread): def __init__(self,queue,score): self.__queue = queue threading.Thread.__init__(self) self.score = score def run(self): while 1: RBL = self.__queue.get() # Are we at the end of the queue? if RBL is None: break self.result = checkRBL("127.0.0.2",RBL,True,5) score.addRBL(RBL,self.result[0],self.result[1]) queue = Queue.Queue(0) score = ConnectionScore() f = open("rbl.list",'r') MEGARBL = [] while 1: line = f.readline().strip() if not line: break MEGARBL.append(line) f.close() for i in range(WORKERS): Worker(queue,score).start() # start a worker for i in MEGARBL: queue.put(i) for i in range(WORKERS): queue.put(None) # add end of queue marker while 1: # wait for the queue??? if queue.empty(): break else: time.sleep(0.1) elapsed = time.time() - starttime rate = len(MEGARBL)/elapsed rate = str(round(rate,2)) elapsed = str(round(elapsed,2)) score.showRBL() print "Checked",str(len(MEGARBL)),"zones in",elapsed,"seconds. (",rate.strip(),"per second )" From steven.bethard at gmail.com Sun Mar 5 19:36:47 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 05 Mar 2006 17:36:47 -0700 Subject: Opening files without closing them In-Reply-To: <1141598002.402189.275520@i40g2000cwc.googlegroups.com> References: <1141598002.402189.275520@i40g2000cwc.googlegroups.com> Message-ID: Sandra-24 wrote: > I was reading over some python code recently, and I saw something like > this: > > contents = open(file).read() > > And of course you can also do: > > open(file, "w").write(obj) > > Why do they no close the files? Is this sloppy programming or is the > file automatically closed when the reference is destroyed (after this > line)? I usually use: > > try: > f = open(file) > contents = f.read() > finally: > f.close() > > But now I am wondering if that is the same thing. Which method would > you rather use? Why? In Python 2.5, you'll write:: with open(file) as f: contents = f.read() and Python will automatically close the file at the end of the with-statement. Observe: Python 2.5a0 (trunk:42857M, Mar 5 2006, 14:50:28) [MSC v.1310 32 bit (Intel)] on win32 >>> from __future__ import with_statement >>> with open('readme.txt') as f: ... contents = f.read() ... >>> f Of course, you have to wait until August or so for Python 2.5: http://www.python.org/peps/pep-0356.html STeVe From diffuser78 at gmail.com Wed Mar 29 17:20:03 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 29 Mar 2006 14:20:03 -0800 Subject: GUI in python Message-ID: <1143670803.148098.21940@z34g2000cwc.googlegroups.com> Hi, I am a python newbie and have used it for about a month. I want to make a simple GUI app in Python ( I take input form user and do processing and show results). Which gui package is good for me. I need to do it quick and I would not want a long learning curve. I was taking look at wxPython, pyGTK etc. Please suggest me the most simplest and easiest one as I dont need super cool aesthetics just a plain simple GUI app. Thanks From kp8 at mac.com Wed Mar 15 22:06:05 2006 From: kp8 at mac.com (kpp9c) Date: 15 Mar 2006 19:06:05 -0800 Subject: Markov process representation In-Reply-To: <1142474078.914549.90870@i40g2000cwc.googlegroups.com> References: <44184edf$1@nntp0.pdx.net> <1142451735.430956.29110@j33g2000cwa.googlegroups.com> <44188597$1@nntp0.pdx.net> <1142469909.951143.253160@j52g2000cwj.googlegroups.com> <7xlkvbqkko.fsf@ruckus.brouhaha.com> <1142474078.914549.90870@i40g2000cwc.googlegroups.com> Message-ID: <1142478365.707309.48700@p10g2000cwp.googlegroups.com> hee hee .... works fine ... but kinda slow on my old machine... really time for a new laptop haha! still this code is so beautiful! *^-^* From sam at nuevageorgia.com Thu Mar 16 18:31:17 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 16 Mar 2006 15:31:17 -0800 Subject: Xah's Edu Corner: The Concepts and Confusions of Pre-fix, In-fix, Post-fix and Fully Functional Notations In-Reply-To: References: <1142490052.127055.50130@v46g2000cwv.googlegroups.com> Message-ID: <1142551877.093595.59760@v46g2000cwv.googlegroups.com> """Not that Mr. Lee has ever shown much interest in feedback, but you pretty well have stick to vanilla ASCII to get your notation through unmangled on newsgroups.""" It is the 21st century, so having to do that oughta inspire some sort of well earned anti Unix rant... :) From fredrik at pythonware.com Wed Mar 22 10:22:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Mar 2006 16:22:33 +0100 Subject: string.upto() and string.from() References: <1143038492.748562.267150@i40g2000cwc.googlegroups.com> Message-ID: ikshefem at gmail.com wrote: > I often need to re-code for myself a small code snippet to define > string.upto() and string.from(), which are used like : > > # canonical examples > > "1234456789".upto("45") > '1234' > > "123456dd987".from('d') > 'd987' > > # if not found, return whole string > > "hello, world !".upto("#") > "hello, world !" > > u"hello, world !".from("#") > u"hello, world !" > > > "123456dd987".from('d',2) # second integer argument > '987' > > # It can be negative, too > > '192.168.179.131'.upto(".",-1) > "192.168.179" > > "192.168.179.131".from('.',-1) > "131" > > # useful example > > bigstring.upto("\n") > "first line of bigstring" > > (I admit I am only using upto, but ...) > > Nothing very complicated to make with find and rfind, but wouldn't this > be handy to have it ready in the common string method ? somewhat related: http://www.python.org/dev/summary/2005-08-16_2005-08-31.html#str-find From sullivanz.pku at gmail.com Sat Mar 11 05:17:06 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 11 Mar 2006 02:17:06 -0800 Subject: Can not find a file in CMD model python when everything is OK in IDLE Message-ID: <1142072226.386475.313160@p10g2000cwp.googlegroups.com> I use python in Windows XP platform. I find that if I write a .py file in a directory, such as windows desktop, in which a file named 'ticket.txt' is located: f=open("\ticket.txt") print f.read() In IDLE, this py file work all right. But if I launch python interpretor in the command shell like this: C:\Documents and Settings\Xiaozhong Zheng>python "C:\Documents and Settings\Xiao zhong Zheng\Desktop\t.py" The interpretor would not find the file. Traceback (most recent call last): File "C:\Documents and Settings\Xiaozhong Zheng\Desktop\t.py", line 1, in ? f=open("ticket.txt") IOError: [Errno 2] No such file or directory: 'ticket.txt' Anyone knows why? In addition, if I start IIS web service that runs .py file as CGI program, then this .py file also works. From hancock at anansispaceworks.com Sat Mar 4 11:46:46 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 4 Mar 2006 10:46:46 -0600 Subject: Python advocacy in scientific computation In-Reply-To: <1141436011.868907.292130@u72g2000cwu.googlegroups.com> References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> Message-ID: <20060304104646.4d67ed15@samwise.anansi> On 3 Mar 2006 17:33:31 -0800 "sturlamolden" wrote: > 1. Time is money. Time is the only thing that a scientist > cannot afford to lose. Licensing fees for Matlab is not an > issue. If we can spend $1,000,000 on specialised equipment > we can pay whatever Mathworks or Lahey charges as well. > However, time spent programming are an issue. (As are time > time spend learning a new language.) "that man speaks for himself!" ;-) Seriously, this depends on the lab. If you're working for a monster pharmaceutical corp or on a military contract on "applied" science (meaning there is a definitely payback expected), then you likely have money to burn. People working in a academic or non-profit lab on "unsexy"/"pure" science, likely don't. Remember that site-licensing usually works on some kind of "per seat" basis (even if you are lucky enough *not* to have a "license server" that constantly tracks usage in order to deny service if and when N+1 users try to use the system, the fee the site fee is still based on the number of expected users). The last science facility I worked at was in considerable debt to a proprietary scientific software producer and struggling to pay the bills. The result was that they had fewer licenses than they wanted and many people simply couldn't use the software when they wanted. I'm not sure what happened in the end, because I left for unrelated reasons before all of that got sorted out, but Python (with a suitable array of add-ons) was definitely on the short-list of replacement software (and partly because I was trying to sell people on it, of course). In fact, if I had one complaint about Python, it was the "with a suitable array of add-ons" caveat. The proprietary alternative had all of that rolled into one package (abeit it glopped into one massive and arcane namespace), whereas there was no "Python Data Language" or whatever that would include all that in one named package that everyone could recognize (I suppose SciPy is trying to achieve that). For similar reasons, Space Telescope Science Institute decided to go full tilt into python development -- they created "numarray" and "pyraf", and they are the ones paying for the "chaco" development contract. Which brings up another point -- whereas with proprietary software (and stuff written using it, like the IDL astronomy library) can leave you with an enormous investment in stuff you can't use, free software development can often be just as cheap, and you get to keep what you make. At one point, I was seriously thinking about trying to write some kind of translator to convert those IDL libs into python libs (quixotic of me?). So why rent when you can own? Scientists certainly do understand all that bit about "seeing further" because you're "standing on the shoulders of giants". With proprietary software, the giants keep getting shot out from under you, which tends to make things a bit harder to keep up with. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From diesch at spamfence.net Sun Mar 26 22:56:59 2006 From: diesch at spamfence.net (Florian Diesch) Date: Mon, 27 Mar 2006 05:56:59 +0200 Subject: detecting drives for windows and linux References: <3uGdnTOPm5PGCrjZnZ2dnUVZ_u2dnZ2d@adelphia.com> <1143317936.422335.294230@u72g2000cwu.googlegroups.com> <1hcspu8.1c95yto1k8d87dN%aleaxit@yahoo.com> Message-ID: <20060327035701.2605.4.NOFFLE@dieschf.news.arcor.de> aleaxit at yahoo.com (Alex Martelli) wrote: > Max wrote: > >> BWill wrote: >> >> > oh, I wasn't expecting a single solution for both platforms, just some >> > good solutions >> > >> > thanks >> >> Are you aware that this idea is somewhat foreign to Linux? (Maybe you >> are and want to do it anyway?) Linux puts the whole file system >> (including mounted iPods, ISOs and NTFS drives) in one hierarchy. > > Yes, but you may still want to distinguish (because, for example, hard > linking doesn't work across filesystems, and mv is not atomic then). Why not use os.stat? > Running a df command is a good simple way to find out what drives are > mounted to what mountpoints -- the mount command is an alternative, but > its output may be slightly harder to parse than df's. Executing df may be expensive if it needs to read some slow file systems. Reading /etc/mtab is not difficult and much faster. Florian -- Das toitsche Usenet ist die Wiederauff?hrung des Drei?igj?hrigen Krieges mit den Mitteln einer Talkshow. [Alexander Bartolich in dcpu] From adam.deprince at gmail.com Fri Mar 24 00:23:19 2006 From: adam.deprince at gmail.com (Adam DePrince) Date: 23 Mar 2006 21:23:19 -0800 Subject: Multiplying all the values in a dictionary In-Reply-To: References: <1143162298.28477.7.camel@cornell> <1143165699.692995.3220@e56g2000cwe.googlegroups.com> Message-ID: <1143177799.833144.108400@t31g2000cwb.googlegroups.com> Wait! It occured to me. Why are we touching the key at all. This is a dictionary with mutable values. [adam at localhost ~]$ python2.4 -mtimeit -s 'd = {(100,500):[5,5], (100,501):[6,6], (100,502):[7,7]}; x = dict(d)' 'for i in x.values(): i[:]=[j*1 for j in i]' 100000 loops, best of 3: 2.79 usec per loop And the best from above: python2.4 -mtimeit -s 'd = {(100,500):[5,5], (100,501):[6,6], > (100,502):[7,7]}; x = dict(d)' 'for key in d: x[key] = [y*2 for y in > d[key]]' 100000 loops, best of 3: 2.85 usec per loop Now, we *know* that all of the values are lists of length 2, so why not say this instead: python2.4 -mtimeit -s 'from numarray import array; d = {(100,500):[5,5], (100,501):[6,6], (100,502):[7,7]}; x = dict(d);j=[0,0]' 'for i in x.values(): j[0]*=1;j[1]*=1' 1000000 loops, best of 3: 1.7 usec per loop Of course, the real code would use *=2, but just to be sure that there is no multiple by 1 optimization: [adam at localhost ~]$ python2.4 -mtimeit 'h=1;h*=2' 10000000 loops, best of 3: 0.143 usec per loop [adam at localhost ~]$ python2.4 -mtimeit 'h=1;h*=1' 10000000 loops, best of 3: 0.144 usec per loop From sybrenUSE at YOURthirdtower.com.imagination Wed Mar 1 03:43:31 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 1 Mar 2006 09:43:31 +0100 Subject: PIL and PSDraw Message-ID: Hi there, I'm experimenting with PIL to create a PostScript file. The end result should be an EPS file with a couple of bar graphs. At this moment, I have a very simple piece of code: ps = PIL.PSDraw.PSDraw(file('demo.ps', 'w')) ps.begin_document() ps.rectangle((0, 0, 650, 150)) ps.end_document() Unfortunately, when looking at 'demo.ps' using ghostview, I see an empty page. This feeling of 'emptyness' is augmented by 'ps2epsi', which tells me: $ ps2epsi demo.ps blank page!! Can anyone tell me what I'm doing wrong? I've just started to use PIL, so if there is something better to create EPS files, please let me know! Sybren The contents of demo.ps: ====================================================================== %!PS-Adobe-3.0 save /showpage { } def %%EndComments %%BeginDocument /S { show } bind def /P { moveto show } bind def /M { moveto } bind def /X { 0 rmoveto } bind def /Y { 0 exch rmoveto } bind def /E { findfont dup maxlength dict begin { 1 index /FID ne { def } { pop pop } ifelse } forall /Encoding exch def dup /FontName exch def currentdict end definefont pop } bind def /F { findfont exch scalefont dup setfont [ exch /setfont cvx ] cvx bind def } bind def /Vm { moveto } bind def /Va { newpath arcn stroke } bind def /Vl { moveto lineto stroke } bind def /Vc { newpath 0 360 arc closepath } bind def /Vr { exch dup 0 rlineto exch dup neg 0 exch rlineto exch neg 0 rlineto 0 exch rlineto 100 div setgray fill 0 setgray } bind def /Tm matrix def /Ve { Tm currentmatrix pop translate scale newpath 0 0 .5 0 360 arc closepath Tm setmatrix } bind def /Vf { currentgray exch setgray fill setgray } bind def %%EndProlog 0 0 M 650 150 0 Vr %%EndDocument restore showpage %%End ====================================================================== -- 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 durango at mail2world.com Fri Mar 31 23:44:14 2006 From: durango at mail2world.com (Mr X) Date: Fri, 31 Mar 2006 20:44:14 -0800 Subject: Python, VB math simple problem Message-ID: <10d7501c65546$ed8b9f60$0a09010a@mail2world.com> Hi looking for help with what should be a fairly simple Python problem, relating to VB inter-operability. Got a great response from a fellow named Matt at help at python.org, pointed me in some good directions - some areas, concerns still foggy on, the below thread is included.... any feedback on this simple dilemma would be very appreciated. Thanks, D thread follows below; ------------------------------------ To: help at python.org Subject: Problem with Python math functions and VB Date: 3/30/2006 9:39:28 PM Download Message Display Headers Printer Friendly Previous | Next Wondering if you might either know how to solve the following. I've a background in Visual Basic, and am using an old version, 4.0, it compiles to a smaller executable which I prefer. I find myself in an odd situation, needing a very simple yet powerful capability of Python for a VB app Im working on. Simply, a large 300 digit number is divided by a smaller number ranging from 1 to 3 digits. I.e; This large 300 digit number is generated as a string from the VB app, and I want to input this somehow from the VB app directly to Python for simple math operations. Where; x = 300 digit number, y = divisor ( say '37') x / 37 I want to divide x by y but I want the remainder of this division to at least 3 or 4 decimal places, so my Python script at the command line; x %y /y. = z So now I want to take the resultant, the full number plus its remainder, and I want to round this number up to the next highest number and divide it by the same constant; z rounded up to next highest number (never the lowest) so z /y = z Long Remove the 'L' at the end, round up the last digit of z = Z Then; Z %y /y. = a Then I want the last five digits of z (not Z) and a truncated at the end, so the last digit before the decimal point and the four digits past the decimal point printed to a text file. I want to be able to open the text file with the VB app and use this data as inputs. ========== Ok, so here is my dilemma, I know VERY litle about Python and a fair bit about VB. Ideally, I'd love to be able to simply have some extremely small executable that just accepts inputs does the calculations above and then spits out the outputs. If it were possible to write some simple lines of math code in Python and then compile these scripts in Python to a Windows compatible executable,that would be fantastic. If I could simply have my VB app, 'call' the name of the tiny Python executable, and then the Python executable just automatically looked for a named text file (created by the VB app) and extracted the 300 digit number from this, then performed the calcs, then spit this data out as a new text file name it created, which I could then use the VB app to open and read from, THAT would be ideal. However, I don't know if Python can compile scripts to an exe? If it can how could I find out how to do this? If it doesn't, how could I get VB to directly pass commands to the Python command line and then automatically extract the outputs? Shelling out from VB to Python would be tough to the command line I think, since the Python command line uses the 'Edit / Mark, Paste' approach to inserting, copy inputs, outputs and this would be virtually untenable, as far as I can tell to automate in a VB shell out routine. So basically, how the heck can I access Pythons ability to perform simple calculations on very large numbers, easily, from within VB 4.0 ? There must be a way, it seems like such a simple think to do, especially since the actual math operations are so simple, straight forward, and would never change..... Any ideas? ------ Matthew, thanks for your response. <-----Original Message-----> >From: Matthew Dixon Cowles >Sent: 3/31/2006 9:41:18 AM >To: durango at mail2world.com >Cc: help at python.org >Subject: Re: [Python-Help] Problem with Python math functions and VB >I'm sure that there's a way to do that, but I'm not familiar with >Visual Basic and I don't know what inter-process communication >facilities it offers. Is there a person or group you might direct me to that has worked with this inter-process communication between VB and Python? >I don't think that Python is going to be able to do that for you out >of the box. Hundreds of digits of floating-point precision is a lot. Could you explain that a bit more, sorry Im not sure what you mean by 'out of the box' ? If I run the Python command line screen in windows and manually type out a very large number, say 180 digits; where 'X' = very large number; X %37 /37. returns what Im after, value wise..... but of course I don't want to do this manually each time for every dividend. >You might find that one of the Python modules that let you use an >extended-precision library would do what you want. GMPY is one: >http://gmpy.sourceforge.net/ Hey, thats interesting, wonder if these modules can be operated on with VB..... >> So now I want to take the resultant, the full number plus its >> remainder, and I want to round this number up >> to the next highest number and divide it by the same constant; > >That's easy enough. > >> I want to be able to open the text file with the VB app and use this >> data as inputs. > >Python can write to a file without any trouble, so it that form of >inter-process communication suits you, you shouldn't have much >trouble. I assume that Visual Basic has an easy way to start a >program and supply it with arguments, so you could have your Python >program get its inputs from sys.argv. What is sys.argv ? Thats really good news. In fact, all I really need for the moment is a python executable that; ================ PYTHON ALGORITHM ABSTRACT a) opens a text file b) reads a string from the file, which is a very large number c) performs simple arithmetic operations; X %37 /37. = y (four digit remainder after decimal point) X /37 = w (quotient as long, the resulting output is stored as a variable, the 'L' suffix tagged on the end of this resultant then gets removed. then the last digit in the quotient resultant string is increased in value by one, rounded upwards = 'Z' then Z %37 /37. = a then, y and a are printed to a text file with hard returns between them. Thats it, thats all I need to do. =================== >Alas, it's not going to be extremely small. There isn't a compiler >from Python to machine code. Py2exe will bundle a Python program, >with everything that it needs to run, into a single executable >archive. But the archive isn't small. Py2exe is at: > >http://www.py2exe.org/ the most important thing is the functionality, I'll sacrifice size if I have to. My guess is this should work based on your comments, because perhaps all I really have to do is have VB dump out the value of the Very large number, `180 to 300 digits or so', to a text file, which then becomes the input data for the Python executable, and then if I simply call the name of the Python executable from VB as an instance, then the Python App runs, spits out the data as a new text file, then the VB app goes and opens the new text file and reads in the values, and voila! There it is. I'm pretty sure I can call the Python app from VB....... the alternative to all this would be to try and feed Python scripts directly to Python from VB, which I have NO idea how to do or where to begin.... and am guessing would be much more messy... I haven't programmed in Python, how would the "PYTHON ALGORITHM ABSTRACT" I describe above look like, code wise? Is this fairly easy for you to describe? >It may be that Python isn't the best solution for you here. Are there >extended-precision libraries for Visual Basic? Alas, none that I know of that are reliable and not incredibly expensive, been looking for years, plus Im hooped because I have to work with VB 4.0 instead of 6 +, guh.... >Regards, >Matt Matt..... good name, why do I always seem to get along with Matts, you people keep popping up in my life and its always a blast! Best regards, D

_______________________________________________________________
Get the FREE email that has everyone talking at http://www.mail2world.com
Unlimited Email Storage – POP3 – Calendar – SMS – Translator – Much More!
-------------- next part -------------- An HTML attachment was scrubbed... URL: From felipe.lessa at gmail.com Sun Mar 19 13:17:17 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 19 Mar 2006 15:17:17 -0300 Subject: Unpythonic? Impossible?? In-Reply-To: <441d8a74$1@nntp0.pdx.net> References: <485ep5Fij70mU1@individual.net> <441d8a74$1@nntp0.pdx.net> Message-ID: <1142792237.13674.1.camel@kenshin> Em Dom, 2006-03-19 ?s 08:54 -0800, Scott David Daniels escreveu: > class A(object): > def __new__(class_, *args, **kwargs): > if class_ is A: > if want_a_B1(*args, **kwargs): > return B1(*args, **kwargs) > elif want_a_B2(*args, **kwargs): > return B2(*args, **kwargs) > return object.__new__(class_) # Use *a,... except for object > > class B1(A): > def __new__(class_, *args, **kwargs): > if class_ is B1: > if want_a_B1(*args, **kwargs): > return B1(*args, **kwargs) > elif want_a_B2(*args, **kwargs): > return B2(*args, **kwargs) > return super(B1, class_).__new__(class_, *args, **kwargs) Why you have that if on B1.__new__? B1 will be created only by A.__new__, which already did a check. -- Felipe. From bdesth.quelquechose at free.quelquepart.fr Tue Mar 21 19:47:36 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 22 Mar 2006 01:47:36 +0100 Subject: doctest, unittest, or if __name__='__main__' In-Reply-To: <1142974528.143287.326360@e56g2000cwe.googlegroups.com> References: <1142974528.143287.326360@e56g2000cwe.googlegroups.com> Message-ID: <442071a3$0$18262$636a55ce@news.free.fr> john_sips_tea at yahoo.com a ?crit : > For writing testcode, it looks like there's three ways that it's > typically done: Actually, there's at least one more > (1). using the doctest module, > > (2). using the unittest module (i.e. "pyunit"), or else > > (3). just putting an "if __name__ = '__main__':" at the bottom of your > module containing code to manually run your class through its paces. (4) using pytest > So, which way is preferred? Seems to me that unittest is the way to go, > at least because it has you separate your test code from the code being > tested. Which may or may not be such a good thing... I prefer to have my tests with the code they're testing. > If unittest is the standard way to write test code, why do we still > have doctest? Because doctest is simple, great, and definitively more pythonic than unittest ? > (I notice there's no mention in PEP 3000 of deprecating > the doctest module). > Hopefully not. From rdh at new.rr.com Mon Mar 27 12:03:33 2006 From: rdh at new.rr.com (DataSmash) Date: 27 Mar 2006 09:03:33 -0800 Subject: front end GUI Message-ID: <1143479013.659230.91000@j33g2000cwa.googlegroups.com> I'm looking for software to create a simple GUI to execute python code for users in the office. The GUI would need a couple text boxes for user input and some option buttons and check boxes. Can anyone recommend free software that doesn't require a huge learning curve? My python skills are probably a 3 or 4 on a scale from 1 to 10. Thanks for your help! R.D. From apardon at forel.vub.ac.be Fri Mar 10 10:20:25 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Mar 2006 15:20:25 GMT Subject: Why python doesn't use syntax like function(, , x) for default parameters? References: <44115054$0$14937$834e42db@reader.greatnowhere.com> <47df47Fd6rifU1@uni-berlin.de> Message-ID: Op 2006-03-10, Diez B. Roggisch schreef : > Antoon Pardon wrote: > >>> >>> Specifying the names of the keyword parameters costs you a little typing >>> once, but saves everybody (including yourself) a lot of grief later when >>> you're trying to figure out what the heck your code does 6 months later. >> >> Could you explain what is so hard in figuring out: >> >> func(,,4) >> >> We sure don't seem to have a problem with figuring out things like >> >> lst[::2] > > That is the usual polemics. Its a HUGE difference if I'm supposed to > remember 2 default values that are 0 and , in a > specialized syntax, Those default values are not 0 and , you may have only experience with situations where they behave as such but that is not the same. > than arbitrary values > f(,,,,,3) > > in some arbitrary function. If you need to know these values then you will need to know them just as much when a keyword is used or when the default values are used later. Calling f(3) or f(arg5=3) Will give you no more a clue about the missing default values than calling f(,,,,,3) At least in the last call you are given a clue about missing arguments. -- Antoon Pardon From greg.kujawa at gmail.com Mon Mar 13 13:49:51 2006 From: greg.kujawa at gmail.com (gregarican) Date: 13 Mar 2006 10:49:51 -0800 Subject: Python Love :) In-Reply-To: <7xirqiqjvh.fsf@ruckus.brouhaha.com> References: <1142099350.122968.35220@i39g2000cwa.googlegroups.com> <1142152271.545155.268170@i40g2000cwc.googlegroups.com> <1142186313.502716.126710@z34g2000cwc.googlegroups.com> <7xacbukz1m.fsf@ruckus.brouhaha.com> <1142272993.822139.45940@u72g2000cwu.googlegroups.com> <7x64mikyif.fsf@ruckus.brouhaha.com> <7xirqiqjvh.fsf@ruckus.brouhaha.com> Message-ID: <1142275791.079043.72700@v46g2000cwv.googlegroups.com> Paul Rubin wrote: > Darn, yes, that's the second time in the past couple weeks I've made > that exact same error in a clpy post. So what's the most concise way > of turning it back into a string? ''.join(list(reversed(a_string))) ? > Bleccch. Use Ruby: print "A String".reverse Just kidding :-)~ From caleb.hattingh at gmail.com Wed Mar 29 15:15:25 2006 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 29 Mar 2006 12:15:25 -0800 Subject: Free Python IDE ? In-Reply-To: <1143653654.234759.133800@j33g2000cwa.googlegroups.com> References: <1143653654.234759.133800@j33g2000cwa.googlegroups.com> Message-ID: <1143663325.006677.167490@u72g2000cwu.googlegroups.com> Hi Ernesto SPE, or Stani's python editor is actually a decent IDE that can lauch the winpdb debugger to step through code, with side windows for locals, and watches and so on. It's not exactly integrated debugging a la Delphi, but in general my need for debugging is much less with python; the few times I have needed debugging, SPE did the job well. I also like that SPE automatically checks my code with tabnanny and pychecker. That way I don't have to do anything extra to use these tools. Oh, and SPE is free. Keep well Caleb From jjl at pobox.com Mon Mar 13 15:02:38 2006 From: jjl at pobox.com (John J. Lee) Date: 13 Mar 2006 20:02:38 +0000 Subject: Why property works only for objects? References: <1hbyfgj.a3p39r1smomavN%aleaxit@yahoo.com> <4412107a$0$22499$636a55ce@news.free.fr> <1hbzzh7.1qlkv8hokpiqzN%aleaxit@yahoo.com> <1hc1abj.1fokrj9826uvjN%aleaxit@yahoo.com> <1hc1fgy.5nq08nvj7qkaN%aleaxit@yahoo.com> <1hc1q2d.44bzrca7iz86N%aleaxit@yahoo.com> <1hc2vld.ete6omjy97iN%aleaxit@yahoo.com> Message-ID: <87zmjukt9d.fsf@pobox.com> Michal Kwiatkowski writes: [...] > "Return a property attribute for new-style classes". After reading a bit > about descriptors I've just assumed that property is a handy way to > create (any) descriptors. Learning that it only creates overriding > descriptors was a bit shocking. I'm not suggesting it's bad behavior, > only that it seemed unexpected for an unaware programmer. What at first > glance looked like a shortcut, turned out to be designed for a specific > use case. [...] Python builtins (especially the newer ones, perhaps) are often targetted fairly tightly on particular use cases. John From sathyaish at gmail.com Mon Mar 20 01:28:30 2006 From: sathyaish at gmail.com (Sathyaish) Date: 19 Mar 2006 22:28:30 -0800 Subject: ** Operator In-Reply-To: <1hcgw5p.1ufznwe1lxeagfN%aleaxit@yahoo.com> References: <1142833145.976550.104830@v46g2000cwv.googlegroups.com> <1142833540.860154.137040@u72g2000cwu.googlegroups.com> <1hcgw5p.1ufznwe1lxeagfN%aleaxit@yahoo.com> Message-ID: <1142836110.460584.170450@g10g2000cwb.googlegroups.com> Thanks, Alex. From jess.austin at gmail.com Thu Mar 9 05:41:57 2006 From: jess.austin at gmail.com (jess.austin at gmail.com) Date: 9 Mar 2006 02:41:57 -0800 Subject: generators shared among threads References: <1141497912.606351.232440@j33g2000cwa.googlegroups.com> <1hbo9a3.1pfr3uy160d79iN%aleaxit@yahoo.com> <7xzmk2nhu9.fsf@ruckus.brouhaha.com> <1141779301.471629.157640@e56g2000cwe.googlegroups.com> Message-ID: <1141900917.279698.207400@i39g2000cwa.googlegroups.com> Bryan, You'll get the same result without the lock. I'm not sure what this indicates. It may show that the contention on the lock and the race condition on i aren't always problems. It may show that generators, at least in CPython 2.4, provide thread safety for free. It does seem to disprove my statement that, "the yield leaves the lock locked". More than that, I don't know. When threading is involved, different runs of the same code can yield different results. Can we be sure that each thread starts where the last one left off? Why wouldn't a thread just start where it had left off before? Of course, this case would have the potential for problems that Alex talked about earlier. Why would a generator object be any more reentrant than a function object? Because it has a gi_frame attribute? Would generators be thread-safe only in CPython? I started the discussion with simpler versions of these same questions. I'm convinced that using Queue is safe, but now I'm not convinced that just using a generator is not safe. cheers, Jess From aleaxit at yahoo.com Sun Mar 19 23:20:50 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 19 Mar 2006 20:20:50 -0800 Subject: String comparison question References: <400BDC416E2A0042AA35DF3919BB8A5115E64F@mail.mtl.proksim.com> Message-ID: <1hcgqzf.1ajeintmz2zs8N%aleaxit@yahoo.com> Michael Spencer wrote: > Olivier Langlois wrote: > > Hi Michael! > > > > Your suggestion is fantastic and is doing exactly what I was looking > > for! Thank you very much. > > There is something that I'm wondering though. Why is the solution you > > proposed wouldn't work with Unicode strings? > > > Simply, that str.translate with two arguments isn't implemented for > unicode strings. I don't know the underlying reason, or how hard it would > be to change. A Unicode's string translate takes a dict argument -- you delete characters by mapping their ord(...) to None. For example: >>> u'banana'.translate({ord('a'):None}) u'bnn' That is in fact much handier, when all you want to do is deleting some characters, than using string.maketrans to create a "null" translation table and passing as the 2nd argument the string of chars to delete. With unicode .translate, you can also translate a character into a STRING...: >>> u'banana'.translate({ord('a'):u'ay'}) u'baynaynay' ...which is simply impossible with plainstring's .translate. Alex From mattjfleming at googlemail.com Sun Mar 12 13:54:30 2006 From: mattjfleming at googlemail.com (mattjfleming at googlemail.com) Date: 12 Mar 2006 10:54:30 -0800 Subject: Class attributes newbie question (before I join a cargocult) In-Reply-To: <1142188575.187032.61390@v46g2000cwv.googlegroups.com> References: <1142188575.187032.61390@v46g2000cwv.googlegroups.com> Message-ID: <1142189670.889371.13000@p10g2000cwp.googlegroups.com> Should't the changeSex method be: def changeSex(self, newsex=""): self.sex = newsex return self.sex You're creating a new instance variable at the moment i.e 'self.mysex' doesn't exist until you call changeSex. From ingmar.ko.andersson at glocalnet.net Sun Mar 19 18:22:04 2006 From: ingmar.ko.andersson at glocalnet.net (koia) Date: 19 Mar 2006 15:22:04 -0800 Subject: Passing parameters to VB Message-ID: <1142810524.578300.116560@g10g2000cwb.googlegroups.com> Hi, I am using win32com for the Python interface to my Excel shreadsheets. When I turn on Macro recordiong in Excel while filling a rectangle with text information, a part of the VB code produced is the following: With Selection.Characters(Start:=1, Length:=11).Font .Name = "Arial" .FontStyle = "Normal" .Size = 10 .Strikethrough = False .Superscript = False .Subscript = False .OutlineFont = False .Shadow = False .Underline = xlUnderlineStyleNone .ColorIndex = xlAutomatic What is the syntax for passing the parameters Start:=1, Length:=11 to VB from a Python function, if I want to control these properties of the text in the Excel spreadsheet? Thanks in advance! / koia From vincent at visualtrans.de Sun Mar 19 16:48:35 2006 From: vincent at visualtrans.de (Vincent Wehren) Date: Sun, 19 Mar 2006 21:48:35 -0000 Subject: Getting .NET SDK to work with Python 2.4.2 References: <1142721716.734835.157980@z34g2000cwc.googlegroups.com> <441D5181.2060103@v.loewis.de> <1142773131.890196.309940@i39g2000cwa.googlegroups.com> <1142778321.691159.120860@j33g2000cwa.googlegroups.com> Message-ID: "Dave" wrote in message news:1142778321.691159.120860 at j33g2000cwa.googlegroups.com... | So this means that I have to download .NET 1.1 SDK. Visual Studio 8 | comes with msvcrt.lib, but im assuming it's the wrong version. | Yes, I'd say so. -- Vincent Wehren From rphillips at engineer.co.summit.oh.us Thu Mar 16 08:29:26 2006 From: rphillips at engineer.co.summit.oh.us (paron) Date: 16 Mar 2006 05:29:26 -0800 Subject: MS word document generator In-Reply-To: <1142455729.303313.34210@j52g2000cwj.googlegroups.com> References: <1142413907.226088.190740@j33g2000cwa.googlegroups.com> <441873b2$0$1337$8fcfb975@news.wanadoo.fr> <1142455729.303313.34210@j52g2000cwj.googlegroups.com> Message-ID: <1142515766.267572.208430@i40g2000cwc.googlegroups.com> You might also consider OpenOffice, which writes to ODF. That way, you're working to a standard. You can script OpenOffice in Python (http://udk.openoffice.org/python/python-bridge.html) . OpenOffice can save in .doc, and does a pretty good job of making a file that most MS Word versions will render properly. According to http://opendocumentfellowship.org/Devel/LibOpenDocument, there is a Python API in development, but I don't know how far along they are. ODF isn't too bad to hack, if you need to do that. Ron From fuzzyman at gmail.com Thu Mar 30 08:56:53 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 30 Mar 2006 05:56:53 -0800 Subject: Countdown from 2 minutes - how? In-Reply-To: <1143725108.307128.16110@v46g2000cwv.googlegroups.com> References: <1143725108.307128.16110@v46g2000cwv.googlegroups.com> Message-ID: <1143727013.387592.33460@i40g2000cwc.googlegroups.com> henrik at wollesens.dk wrote: > Hi. > > Can anyone tell me the python code for a simple countdown from eg. 2.00 > minutes. > > It should be printet out to the screen. > When it is finished it should write "Time is up" > > Hope you can help. > You need the module ``time`` : import time start = time.time() lastprinted = 0 finish = start + 120 while time.time() < finish: now = int(time.time()) if now != lastprinted: print int(finish - now) lastprinted = now time.sleep(0.5) # this stops the system hanging whilst this is running print "Time is up" HTH Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Henrik From python at rcn.com Mon Mar 13 20:24:31 2006 From: python at rcn.com (Raymond Hettinger) Date: 13 Mar 2006 17:24:31 -0800 Subject: Q's: pythonD and range(1,12) In-Reply-To: <060314000104512.14Mar06$rookswood@suburbian.com> References: <060314000104512.14Mar06$rookswood@suburbian.com> Message-ID: <1142299471.104100.40890@i40g2000cwc.googlegroups.com> John Savage wrote: > Could > someone please explain the rationale behind python designers' thinking > in deciding the function "range(1,12)" should return the sequence 1 to > 11 rather than the more intuitively-useful 1 to 12?? There are several ways to do this, closed intervals, half-open intervals, zero indexed, indexed from one, etc. Each way has its own strengths and weaknesses. Guido chose the one he liked best and applied the concept consistently throughout the language (slicing, etc). His choice has some nice properties such as len(range(n))==n and range(0,i)+range(i,n)==range(n). The downside of the half-open interval approach is that it can be confusing when counting backwards: range(n-1, -1, -1). Accordingly, the builtin reversed() function was introduced so you could write this in a more intuitive and readable manner: list(reversed(range(n))). Some of this is a matter of taste and a matter of what you're used to using, so the answer to what is the "more intuitively-useful" varies depending on who is answering the question. Raymond From felipe.lessa at gmail.com Thu Mar 23 20:17:07 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Thu, 23 Mar 2006 22:17:07 -0300 Subject: Question about raw string and regex In-Reply-To: <1143162709.817584.192910@g10g2000cwb.googlegroups.com> References: <1143162709.817584.192910@g10g2000cwb.googlegroups.com> Message-ID: <1143163027.28762.8.camel@kenshin> Em Qui, 2006-03-23 ?s 17:11 -0800, jlowery at blarg.net escreveu: > Since the classexpr isn't a raw string (not r prefix), doesn't the \t > get converted to a tab character before it gets to the regex compiler? >>> print '^\([ \t]*class +[a-zA-Z0-9_]+\) *( *) *\(\(=.*\)?\):' ^\([ ]*class +[a-zA-Z0-9_]+\) *( *) *\(\(=.*\)?\): Yes... maybe that's the intention? -- Felipe. From arne at citde.net Thu Mar 23 16:49:48 2006 From: arne at citde.net (Arne Ludwig) Date: 23 Mar 2006 13:49:48 -0800 Subject: Remove integer from float number In-Reply-To: References: <1143142664.507941.130240@g10g2000cwb.googlegroups.com> <4422FAA9.50506@websafe.com> <4422fcac@news.eftel.com> Message-ID: <1143150588.878395.228200@t31g2000cwb.googlegroups.com> With that terse description and the subject line I would interpret the OP like so: >>> print re.sub(".*\.",".","0.666") .666 >>> print re.sub(".*\.",".","123.666") .666 From steve at holdenweb.com Thu Mar 9 15:57:26 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 09 Mar 2006 20:57:26 +0000 Subject: Any python HTML generator libs? In-Reply-To: <1141936438.584242.129220@z34g2000cwc.googlegroups.com> References: <1141936438.584242.129220@z34g2000cwc.googlegroups.com> Message-ID: Sullivan WxPyQtKinter wrote: > Hi, everyone. Simply put, what I need most now is a python lib to > generate simple HTML. > > I am now using XML to store my lab report records. I found python > really convinient to manipulate XML, so I want to make a small on-line > CGI program to help my colleagues to build their lab report records > into XML, for storage, HTML display (for others to browse) and search. > > With python's standard lib, the DOM object could realize the XML > storage and search quite easily, but for HTML generation, it is a > great headache. > > I tried to turn to the in-line server-side python script PSP(something > like asp and php) instead of CGI. However, since the report data is > always of very complex data structures, it is really hard to write most > things in-line. For example, a PCR reaction is expected to be shown in > this format or alike on a web browser: > > PCR > Sample: Sm1032 > Operater: SullivanZ > TimeStamp: hh:mm mm-dd-yyyy > Reaction: > Reagent1: > Name:XXXX > Concentration:XXXX mM > Volumn:XXX uL > Reagent2: > ........................ > ........................ > > Since there are hundreds of PCR reaction and other operations in the > lab report, in-line PSP is not a suitable solution. But writing HTML > directly with print statement is a great pain. > > Will XSTL be useful? Is my problem somewho related with XML-SIG? > Looking forward to your precious suggestion. > The triple-quoted string with string substitution is your friend. Try writing something(s) like: results = {'secnum': 1, 'type': 'string', 'color': 'blue'} print """\

Section %(secnum)s

Elements of type %(type)s should be coloured %(color)s

""" % results Alternatively you might want to take a look at the HTMLgen module. It's old, but still usable. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From max at alcyone.com Thu Mar 23 23:14:53 2006 From: max at alcyone.com (Erik Max Francis) Date: Thu, 23 Mar 2006 20:14:53 -0800 Subject: Strings and % sign fails - Help Please In-Reply-To: <87d5gcr0ng.fsf@ieee.org> References: <1143168531.461348.130160@t31g2000cwb.googlegroups.com> <87lkv0r1lk.fsf@ieee.org> <1143169736.507783.95460@z34g2000cwc.googlegroups.com> <87d5gcr0ng.fsf@ieee.org> Message-ID: Jorge Godoy wrote: > siasookhteh at gmail.com writes: > >> heh.. It works except I am using psycopg.Binary(somebinarystructure), >> and I am not really doing it by hand to just add the extra %, and >> psycopg.Binary doesn't do it. I'd imagine it's a bug with psycopg >> package. Any quick way to project a string from freak '%' problems? > > Try using r"string '%'"... Raw strings don't have anything to do with format specifiers. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis If the sky should fall, hold up your hands. -- (a Spanish proverb) From __peter__ at web.de Mon Mar 20 06:21:55 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 20 Mar 2006 12:21:55 +0100 Subject: Chained Comparisons References: <1142835847.348629.177950@z34g2000cwc.googlegroups.com> <441e607d$1@news.eftel.com> <1142842595.057727.298380@z34g2000cwc.googlegroups.com> Message-ID: Sathyaish wrote: > I) What does the following expression evaluate to? > > a < b == c > > 1) (a < b) and (b == c) > 2) (a < b) or (b == c) then later > 1) It is easier to learn through an interactive medium like a forum; There is a convenient alternative to asking basic questions on c.l.py or ploughing through formal docs. When you have a clear conception of the possible outcomes it is also reliable. >>> 1 < 2 == 3 False It can't be 'or' then. In short, the interactive prompt is *the* tool to learn about language features and libraries. Peter From bdesth.quelquechose at free.quelquepart.fr Wed Mar 22 19:04:39 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 23 Mar 2006 01:04:39 +0100 Subject: read a file line by line using readline() In-Reply-To: <1143051933.896659.179540@g10g2000cwb.googlegroups.com> References: <1143051933.896659.179540@g10g2000cwb.googlegroups.com> Message-ID: <4421b902$0$27269$626a54ce@news.free.fr> Phoe6 a ?crit : > Hi all, > I just read the manual and got to know I can use a for loop to iterate > through the lines in the file. > > But so far, I was strugling with the following: > > import os > file = open('File1.txt','r') 'file' is the builtin type for file objects (like the one returned by open()). Avoid using it as an identifier, this shadows the file type. > line = file.readline() > while line !=' ': As Thomas pointed out, this is not an empty string !-) Also, this is not a for loop... > print line > line = file.readline() Do yourself a favor, use a for loop. Also, a file opened in read mode is already an iterator : f = open('path/to/file') for line in f: do_something_with(line) f.close() From just at xs4all.nl Thu Mar 9 10:36:39 2006 From: just at xs4all.nl (Just) Date: Thu, 09 Mar 2006 16:36:39 +0100 Subject: First script, please comment and advise References: <1141917596.011498.311500@p10g2000cwp.googlegroups.com> Message-ID: In article <1141917596.011498.311500 at p10g2000cwp.googlegroups.com>, bearophileHUGS at lycos.com wrote: > My version is similar to Just one: > > from random import shuffle > > def scramble_text(text): > """Return the words in input text string scrambled > except for the first and last letter.""" > def scramble_word(word): > if len(word) < 4: return word > core = list(word[1:-1]) > shuffle(core) > return word[0] + "".join(core) + word[-1] > > return " ".join(map(scramble_word, text.split())) > > print scramble_text(scramble_text.__doc__) Your text split behaves completely different from the original; I think it was intentional that any puntuation wasn't affected. Btw. I find the use of a nested function here completely bogus: you don't need the surrounding scope. Just From steve at holdenweb.com Wed Mar 8 01:57:54 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 08 Mar 2006 06:57:54 +0000 Subject: Reading binary from a file... In-Reply-To: <1141797306.053658.253950@p10g2000cwp.googlegroups.com> References: <1141797306.053658.253950@p10g2000cwp.googlegroups.com> Message-ID: KraftDiner wrote: > Hi! > In python I'm able to read in binary data from a file. > data = file.read() # Reads in an entire file. > Note that you should open the file in binary mode to be platform-agnostic and as portable as possible. (Just in case you aren't). > However the data is 16bits per sample and python is storing the > data in a string. How do I convert that 8bit data into a list of 16 > bit integers? > > Note: I want generic python lists or tupels not numpy or numeric etc > etc... > You really want the struct module here. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From g.brandl-nospam at gmx.net Mon Mar 27 05:56:55 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Mon, 27 Mar 2006 12:56:55 +0200 Subject: __slots__ In-Reply-To: References: <1143106365.996810.269780@z34g2000cwc.googlegroups.com> <1hcqwk5.9z7uv51pwbdrbN%aleaxit@yahoo.com> <1hcr1bw.1dywgpk1l0cpafN%aleaxit@yahoo.com> Message-ID: <48punoFlc3utU1@individual.net> Antoon Pardon wrote: > Op 2006-03-25, John J. Lee schreef : >> aleaxit at yahoo.com (Alex Martelli) writes: >> [...] >>> you should be using pychecker or pylint >> [...] >> >> I'm curious, as somebody who doesn't regularly use these tools: How do >> they fit into your workflow? Do you run them every few hours, every >> day, every time you run functional tests, every release, every so >> often, on gut feeling about when it's likely to catch problems...? >> >> How do you cope with spurious warnings? Does it involve tweaking code >> to quell warnings? Keeping suppression lists? Maintaining special >> invocations of pychecker / pylint per-project? Do they cope well with >> other people's code who do not use these tools? > > IMO they don't cope well unless you adapt to what they expect. > > I just tested the two. > > pylint gave me countless warnings because I use two space to indent > instead of four. It also didn't like that I used uppercase letters > in my identifiers. That there was no space after a comma or > around an operator was a problem too. Pylint knows different types of issues, these are "code style" issues and can be - turned off - configured to what you like. They help getting your coding style consistent and default to PEP8 style. > That I use the same name for the index variable of for loops in > different scopes is also warned about. Well, everything that _could_ be problematic _or_ confuse a reader is warned about. Pretty good in my eyes. > Pychecker also warns about these shadowed variable. Pychecker > goes even so far to warn you that a local variable in an imported > module is shadowing a global variable of yours. Like the following > line: > > /usr/lib/python2.3/random.py:247: Local variable (i) shadows global > defined on line 43 in file demo1a.py That's odd. How are the two modules related? > So it seems pychecker thinks I shouldn't use something like > > for i in lst: > ... > > in my code at the global level because some module in the standard > library has a function with a local i. > > Pychecker also froze on my system. Pychecker imports the modules. Thus these things can happen when a module expects not to be imported as-is. > I don't recommend the use of these tools. Well, then I don't recommend anyone reading your code Georg From n.estner at gmx.de Sat Mar 18 11:10:11 2006 From: n.estner at gmx.de (nikie) Date: 18 Mar 2006 08:10:11 -0800 Subject: Linear regression in NumPy In-Reply-To: <%PVSf.52$Qm2.24@trndny03> References: <1142628938.982098.239850@u72g2000cwu.googlegroups.com> <1142631926.353064.206010@p10g2000cwp.googlegroups.com> <1142639157.977175.257900@u72g2000cwu.googlegroups.com> <%PVSf.52$Qm2.24@trndny03> Message-ID: <1142698211.185324.154130@j33g2000cwa.googlegroups.com> Thank you! THAT's what I've been looking for from the start! From aleaxit at yahoo.com Wed Mar 29 21:32:51 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 29 Mar 2006 18:32:51 -0800 Subject: No Cookie: how to implement session? References: <1143567624.164865.71730@v46g2000cwv.googlegroups.com> <9uvi225dlg8kd892jpfg8mqne6chnavus6@4ax.com> <1143611572.058029.31080@u72g2000cwu.googlegroups.com> <1hcxl45.8om0dc176mbu3N%aleaxit@yahoo.com> Message-ID: <1hcz4gs.zr4za5i9ey4dN%aleaxit@yahoo.com> Aahz wrote: > In article <1hcxl45.8om0dc176mbu3N%aleaxit at yahoo.com>, > Alex Martelli wrote: > > > >Cookies aren't "tricks" -- they are THE standard, architected solution > >for session persistence in HTTP 1.1 -- people who disable them are > >saying they do not *WANT* persistent sessions... on their heads be it. > > OTOH, there are too many sites out there that mandate persistent sessions > for no good reason. NetFlix being a canonical example (before logging > in, that is). Sites should degrade gracefully in the absence of cookies > unless they are absolutely essential for site operation. I entirely agree with you -- do you mean netflix just won't work if I try to visit it, not log in, with cookies disabled in my browser?! Alex From paddy3118 at netscape.net Fri Mar 24 15:59:34 2006 From: paddy3118 at netscape.net (Paddy) Date: 24 Mar 2006 12:59:34 -0800 Subject: What's the best way to learn perl for a python programmer? In-Reply-To: <1143213419.350106.274060@g10g2000cwb.googlegroups.com> References: <1143213419.350106.274060@g10g2000cwb.googlegroups.com> Message-ID: <1143233974.085083.198280@e56g2000cwe.googlegroups.com> Tell 'them' you need a uniform installation of your scipting language across all servers to ensure correct operation of your script then ensure its python that gets loaded ;-) I took a course in perl from Well House Consultants in the UK, which was good; then had an immediate use for perl, which helped me remember. I used the Well House manual and the Camel book for reference. (http://www.wellho.net/ - Tell Graham Paddy sent you). P.S. I don't have any connection to Well House, apart from learning Perl through them. - Paddy. From zeaphoo at gmail.com Sat Mar 11 22:09:25 2006 From: zeaphoo at gmail.com (Wei Zhuo) Date: Sun, 12 Mar 2006 11:09:25 +0800 Subject: Jython In-Reply-To: References: Message-ID: jython2.2 is under developing, you can download the alpha version in sourceforge. 2006/3/12, rtilley : > > Is development still going on with Jython? Version 2.1 came out in 2001 > and it's still the most current stable release. > > Thanks! > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVETHIScyber.com.au Sat Mar 4 02:20:51 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 04 Mar 2006 18:20:51 +1100 Subject: idea: add an asynchronous exception class References: <7x3bhysotm.fsf_-_@ruckus.brouhaha.com> Message-ID: On Fri, 03 Mar 2006 22:31:49 -0800, Paul Rubin wrote: > I'd like to suggest adding a builtin abstract class to Python called > AsynchronousException, which would be a subclass of Exception. [snip rationale] +1 on this. -- Steven. From pmetzger at bellsouth.net Wed Mar 1 09:53:27 2006 From: pmetzger at bellsouth.net (Paul Metzger) Date: Wed, 01 Mar 2006 08:53:27 -0600 Subject: newbie question In-Reply-To: <1141242700.105093.317210@t39g2000cwt.googlegroups.com> References: <1141242700.105093.317210@t39g2000cwt.googlegroups.com> Message-ID: <1141224808.32332.20.camel@Aries.anubis.pbmhr.com> > I'm brand new to using/playing with Python, and I have what is likely a > very simple question but can't seem to figure it out. > Python is fun and it's easier to use a real OS to develop the programs, then if need be, not that difficult to move them to windows:) > I wrote up a script in my preferred text editor. It contains maybe ten > lines of code. I want to be able to execute those code lines with a > single command either from the inline mode or from IDLE. How do I do > this? I saved the file (myscript.py) in a folder that I've specified > in my PYTHONPATH environment variable, and when I type If you are going to use a text editor to do python with, may I suggest gVim, or vim it will take care of ALOT of syntax errors dure to indentation for you. Grant it I am a command line junky, but still... > > >>> import myscript > > the script runs. If, later during the same session, I type > > >>> myscript > > all I get for output is > > documents\Python Modules\myscript.pyc'> > > Somwhere in the beginning tutorial there's this line: > > "The script can be given a executable mode, or permission, using the > chmod command: > > $ chmod +x myscript.py" > Ok, the above seems to me like you are useing windows. If so, the chmod commands are going to be just about worthless. If you install unix services for windows, you will get some functionality, but not also, and still what's the point. Linux is free and much more stable, secure, etc... > Which I took to mean that if I enter that I would be able to do what I > wanted. But no, it just highlights 'myscript' in red and says it's a > syntax error. > > What am I missing? OK, excuseing my editorial comments above, here is what I see and correct me if I'm wrong. 1) you use windows 2) You have not been around any OS other than windows and I mean this as no insult, just making sure I understand you. The answer to your questions are as follows. In Unix/Linux/XXix/Solaris and most anyother unixy(yes that's a word, I just made it up) OS you can add the first line of the script being something like #!/usr/bin/python or where ever you installed python to, then FROM A COMMAND LINE run chmod and it will make the script executable. What happens is when you tell the script to run, it looks at the line and then knows where to pull the inter. from. the # just comments it out so it don't try to run it with the rest of the script, the ! tells the computer to pay attention to it. As far as I know, you cannot do this in Windows. to run it in a single command, you would have to either compile it with py2exe which will give you the .exe and a dll or two or you can simple make a batch file that would look something like @ECHO OFF python script.py the @ECHO OFF is not needed, but I think it looks better and more professional, but that is just me. I do realize I have rambled on for a while here but I do hope it helps. I have been out of the python loop for a while, but am being forced back into it, which really don't hurt my feelings at all, just had to wait for a project that required it:) Anyway if you dont understand anything just let me know and i'll try to do a better job explaining it. Paul From sullivanz.pku at gmail.com Tue Mar 28 13:24:23 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 28 Mar 2006 10:24:23 -0800 Subject: CGI redirection: let us discuss it further In-Reply-To: <1143566506.253970.172230@z34g2000cwc.googlegroups.com> References: <1143480299.024145.272600@u72g2000cwu.googlegroups.com> <1143566506.253970.172230@z34g2000cwc.googlegroups.com> Message-ID: <1143570263.164844.129800@z34g2000cwc.googlegroups.com> > Just read the name of the server (os.environ['SERVER_NAME']) to work > out what absolute URL to redirect to, whist still being portable. > > Here's some code I dug up that should also cope with non-default ports > and SSL, if that's of any use: > > ssl= os.environ.get('HTTPS', 'off') not in ('', 'off', 'false', 'no') > scheme= ['http', 'https'][ssl] > port= ['80', '443'][ssl] > host= os.environ.get('SERVER_NAME', 'localhost') > url= '%s://%s:%s' % (scheme, host, os.environ.get('SERVER_PORT', > port)) > if url.endswith(':'+port): > server= server[:-(len(port)+1)] > url+= path > > (You *can* pass relative URLs back to the web server in a Location: > header, but this should do an internal redirect inside the server, > which may not be what you want.) Sorry I do not quite understand what is the difference between an internal redirection and an external one? > > -- > And Clover > mailto:and at doxdesk.com > http://www.doxdesk.com/ From onurb at xiludom.gro Fri Mar 31 11:34:03 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 31 Mar 2006 18:34:03 +0200 Subject: member variables in python In-Reply-To: <1143821291.915307.157060@g10g2000cwb.googlegroups.com> References: <1143819190.360242.314830@z34g2000cwc.googlegroups.com> <442d4b03$1_2@newspeer2.tds.net> <1143821291.915307.157060@g10g2000cwb.googlegroups.com> Message-ID: <442d5a3e$0$20955$636a55ce@news.free.fr> PyPK wrote: > ok I reason I was going with globals is that i use this variable in > another class something like this along with above > > testflag = 0 > > class AA: > def __init__(...): > > def methos(self,...): > global testflag > testflag = xx > > class BB: > def __init__(...): > > def method2(..): > if testflag: > print "do this" Seems that you're looking for a logging package (hint: there's one in the standard lib). > is there a better way to access this if we go with what you mentioned > in another class .. > I wanted to avoid globals thats the reason i am looking for better > solution .. > A general solution would be a combination of 1/ a Singleton or Monostate (for storing application-wide settings) and 2/ a method decorator managing additionnal responsabilities according to the values of 1. There are examples of Singleton/Borg/Monostate/whatnot in the Python cookbook and elsewhere - as usual, google is your friend - and a Q&D example of decorator doing this kind of jobs in the decorator library http://wiki.python.org/moin/PythonDecoratorLibrary 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 limodou at gmail.com Tue Mar 21 20:14:55 2006 From: limodou at gmail.com (limodou) Date: Wed, 22 Mar 2006 09:14:55 +0800 Subject: py web-app-frameworks without a rdbms... In-Reply-To: <1142989572.483475.158570@e56g2000cwe.googlegroups.com> References: <1142989572.483475.158570@e56g2000cwe.googlegroups.com> Message-ID: <505f13c0603211714g4079124frb546dd11e10ab8e6@mail.gmail.com> On 21 Mar 2006 17:06:12 -0800, venkatbo at yahoo.com wrote: > Hi folks, > > Of TurboGers & Django WAF candidates, which one would be easier to use > in an environment where the data/content doesn't come an RDBMS, but > from other server-side apps... If these are not good candidates, could > you suggest appropriate ones... > > TIA, > /venkat > If you don't want to use RDBMS, I think Karrigell is better. Many features of Django and TurboGears relate to database. -- I like python! My Blog: http://www.donews.net/limodou NewEdit Maillist: http://groups.google.com/group/NewEdit From bdesth.quelquechose at free.quelquepart.fr Sun Mar 26 18:48:58 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 27 Mar 2006 01:48:58 +0200 Subject: Accessing func_name from inside a function In-Reply-To: <1143309619.566327.173640@j33g2000cwa.googlegroups.com> References: <1143309619.566327.173640@j33g2000cwa.googlegroups.com> Message-ID: <4426fb19$0$18279$636a55ce@news.free.fr> James Thiele a ?crit : > I'd like to access the name of a function from inside the function. My > first idea didn't work. > > >>>>def foo(): > > ... print func_name > ... > >>>>foo() > > Traceback (most recent call last): > File "", line 1, in ? > File "", line 2, in foo > NameError: global name 'func_name' is not defined > > My second attempt works but looks ugly. > > >>>>def foo(): > > ... import inspect > ... print inspect.stack()[0][3] > ... > >>>>foo() > > foo > > Is there a standard way of getting the name of a function from inside > the function? > You've already got good answers. Now here's another workaround: class _FooFunction(object): def __call__(self): print self.__class__.__name__ foo = _FooFunction() From arne at citde.net Sat Mar 25 17:00:17 2006 From: arne at citde.net (Arne Ludwig) Date: 25 Mar 2006 14:00:17 -0800 Subject: using regex to pull out email addresses In-Reply-To: References: Message-ID: <1143324017.297853.72150@u72g2000cwu.googlegroups.com> >>> senderlist="na nu ni at no.com hu ji at ja ku at pi.pa.po.jp fa hu" >>> print [ s[0] for s in re.findall("(\w+@(\w+\.)+\w+)",senderlist) ] ['ni at no.com', 'ku at pi.pa.po.jp'] From __peter__ at web.de Wed Mar 22 14:02:30 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Mar 2006 20:02:30 +0100 Subject: Conversion from string to integer References: <1143052880.190153.287940@j33g2000cwa.googlegroups.com> Message-ID: xkenneth wrote: > I've been attempting to write a serial program in python. I talk to > a custom designed bit of hardware that sends me back groups that are 2 > bytes in length. When i recieve them using either pySerial or USPP i'm > not sure how python interprets them. Both of the bytes should be > interpreted as one integer. I store each of the two bytes in a python > array. Here is an example of the data as printed in a terminal. > > ['\x1dz', '\xa8<', '\x89{', '}O', 'r\xaf', '\x83\xcd', '\x81\xba', > '\x00\x02', '\x00\x00', '\x00\x00', '\x00\x00'] > > As you can see it either chooses to represent one byte in hex or one in > ascii or both in hex etc. I'm just not sure how to get this into an > integer format. Your data consists entirely of two-byte strings; don't get fooled by the way Python represents them. To convert them you need struct.unpack() which seems to be in high demand today: >>> data = ['\x1dz', '\xa8<', '\x89{', '}O', 'r\xaf', '\x83\xcd', '\x81\xba', ... '\x00\x02', '\x00\x00', '\x00\x00', '\x00\x00'] >>> print [struct.unpack("h", s)[0] for s in data] [7546, -22468, -30341, 32079, 29359, -31795, -32326, 2, 0, 0, 0] Of course "h" is only one of the candidates for the format parameter. See http://docs.python.org/lib/module-struct.html for the complete list. Peter From gslindstrom at gmail.com Wed Mar 8 21:55:06 2006 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Wed, 8 Mar 2006 20:55:06 -0600 Subject: Gathering screen output Message-ID: <57aa55060603081855x277d2672y827678447e1c63b4@mail.gmail.com> Hello- I'm running Python 2.4 on windows xp "professional" and seem to recall there is a way to kick off system command (or any external routine) and then collect the screen output back into the calling python routine for analysis. I've look and googled but have come up lacking. Please tell me this is not a flashback to my days coding with another "P" language... Thanks for your help! --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From admin at loial.co.uk Mon Mar 27 08:22:23 2006 From: admin at loial.co.uk (loial) Date: 27 Mar 2006 05:22:23 -0800 Subject: Python, equivalent of set command Message-ID: <1143465742.940093.35720@i40g2000cwc.googlegroups.com> In unix shell script I can do the following to get the status and values returned by a unix command OUTPUT=`some unix command` STATUS=$? if [ $STATUS -ne 0 ] then exit 1 else set $OUTPUT VAL1=$1 VAL2=$2 VAL3=$3 fi How can I achieve the same in python? I know how to run it via the os.system command and return the status, but how do I return the values too? From g.horvath at gmx.at Thu Mar 2 10:32:54 2006 From: g.horvath at gmx.at (Gregor Horvath) Date: Thu, 02 Mar 2006 16:32:54 +0100 Subject: _tkinter.TclError: can't set "PY_VAR0": invalid command name "-1210125972check" Message-ID: <66a88$44071027$506c2949$9589@news.chello.at> Hi, I searched the web and docs but cannot figure out whats wrong with this code: #!/usr/bin/python import Tkinter as Tk class testtk(Tk.Frame): def __init__(self): self.root = Tk.Tk() Tk.Frame.__init__(self,self.root) self.frame = Tk.Frame(self.root) self.var = Tk.StringVar() self.var.trace_variable('w',self.check) Tk.Entry(self.frame, textvariable = self.var).pack() self.frame.pack() Tk.mainloop() def check(): pass if __name__ == "__main__": t = testtk() t.var.set("TEST") Result: Traceback (most recent call last): File "", line 22, in ? File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 191, in set return self._tk.globalsetvar(self._name, value) _tkinter.TclError: can't set "PY_VAR0": invalid command name "-1210125972check" Any ideas, why I cant set the variable var? -- Greg From tomerfiliba at gmail.com Fri Mar 10 09:48:03 2006 From: tomerfiliba at gmail.com (tomerfiliba at gmail.com) Date: 10 Mar 2006 06:48:03 -0800 Subject: why use special config formats? Message-ID: <1142002082.976945.261900@e56g2000cwe.googlegroups.com> hey i've been seeing lots of config-file-readers for python. be it ConfigObj (http://www.voidspace.org.uk/python/configobj.html) or the like. seems like a trend to me. i came to this conclusion a long time ago: YOU DON'T NEED CONFIG FILES FOR PYTHON. why re-invent stuff and parse text by yourself, why the interpreter can do it for you? and anyway, i find this a very ugly format: http://www.voidspace.org.uk/python/configobj.html#the-config-file-format there are two use cases for configuration: static vs. dynamic configuration. for the most common case, static configuration, you just have a human-edited config file holding key-and-value pairs. so just add to your package a file called config.py, and import it. for example, if that's our package structure: PyApache/ __init__.py config.py server.py then server.py would do: ... import config listener_sock.bind((config.host, config.port)) ... and config.py would look like: # the port to bind to port = 80 host = "localhost" timeout = 300 enable_keep_alives = False options = [1, 2, 3] ... isn't python suitable enough to hold your configuration? the second case, dynamic configuration, is when you need to alter your configuration at runtime or programatically, so the configuration doesnt need to be human-readable. for that case -- use pickle. and Bunch (as shown on the aspn python cookbook) class Bunch(object): def __init__(self, **kw): self.__dict__.update(kw) create the initial config file: config = Bunch(port = 80, host = "localhost", timeout = 300, ...) pickle.dump(open("config.pkl", "wb"), config) of course you can nest Bunch'es inside one another, i.e., config = Bunch( # global config port = 80, host = "localhost", # this is per-user configuration users = { "malcom_x" : Bunch( http_path = "/home/joe/httpdocs", cgi_path = "/home/joe/cgi-bin", options = ["i love lucy", "bush is gay"] ), ... }, ... ) and now you use it: # global configuration config = pickle.load(open("config.pkl")) listener_sock.bind((config.host, config.port)) # and per-user configuration from getpass import getuser print config.users[getuser()].http_path ... that way, if you need to programatically change your configuration, just change and pickle.dump() it. hope it helps, -tomer From onurb at xiludom.gro Mon Mar 20 14:43:37 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 20 Mar 2006 20:43:37 +0100 Subject: user-supplied locals dict for function execution? In-Reply-To: <1142879594.924929.96440@v46g2000cwv.googlegroups.com> References: <1142875454.906993.126370@v46g2000cwv.googlegroups.com> <441eedbd$0$20865$636a55ce@news.free.fr> <1142879594.924929.96440@v46g2000cwv.googlegroups.com> Message-ID: <441f0623$0$23127$626a54ce@news.free.fr> Lonnie Princehouse wrote: >>What's your use case exactly ? > > > I'm trying to use a function to implicitly update a dictionary. I think this was pretty obvious. What I wonder is *why* you want/think you need to do such a thing -I don't mean there can't be no good reason to do so, but this has to be a pretty uncommon use case, and some of the gurus here may point you to (possibly other and possibly better) solutions if you give a bit more context. And BTW, please, lauch your python shell and type 'import this', then read carefully. > The > whole point is to avoid the normal dictionary semantics, Yes, but *why ?* -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From exter_c at hotmail.com Thu Mar 30 04:48:58 2006 From: exter_c at hotmail.com (Johhny) Date: 30 Mar 2006 01:48:58 -0800 Subject: regular expressions and matches Message-ID: <1143712138.219521.90470@v46g2000cwv.googlegroups.com> Hello, I have recently written a small function that will verify that an IP address is valid. ==SNIP== import re ipAddress = raw_input('IP Address : ') def validateIP(ipAddress): ipRegex = r"^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$" re_ip = re.compile(ipRegex) match = re_ip.match(ipAddress) if not match: print "an error has occured with ipAddress" return match else: return match print(validateIP(ipAddress)) ==SNIP== I was having issues trying to get my code working so that I could pass the IP addresses and it would return a true or false. When it matches I get something that looks like this. python ip_valid.py IP Address : 192.158.1.1 <_sre.SRE_Match object at 0xb7de8c80> As I am still attempting to learn python I am interested to know how I could get the above to return a true or false if it matches or does not match the IP address. I would also like to expand that so that if the IP is wrong it requests the IP address again and recalls the function. I have done the same thing in php very easily but python appears to be getting the better of me. Any assistance and advice would be greatly appreciated. Regards, Johhny From florasol at hotmail.com Sun Mar 5 13:04:43 2006 From: florasol at hotmail.com (Francois) Date: 5 Mar 2006 10:04:43 -0800 Subject: Why I chose Python over Ruby In-Reply-To: <1hbpvkf.1lnu9vjfdg3j2N%aleaxit@yahoo.com> References: <1141573450.667103.8930@z34g2000cwc.googlegroups.com> <1hbpvkf.1lnu9vjfdg3j2N%aleaxit@yahoo.com> Message-ID: <1141581883.269704.72390@e56g2000cwe.googlegroups.com> Alex Martelli wrote: > > I also share your preference for a single namespace for callable and > non-callable values, as in Python (and Scheme, Lisp, C++, ...), rather > than disjoint namespaces as in Ruby (and Smalltalk), but I do not see it > as a question of rigor and consistency at all -- e.g., I do not perceive > Smalltalk as less rigorous or consistent than C++, on the contrary. > > So, I agree with your choice, and I think I understand your motivations, > but I do not entirely share your motivations, personally speaking. > Thanks Alex for your excellent explanations. I have the Python Cookbook 2nd Ed., and I highly appreciate your knowledge and experience. I guess my choice of words "rigor and consistency" was not very good. In this context "rigor" meant enforcing rules (for example having to use parentheses to call a method) to prevent ambiguity rather than depending on heuristics. Also "consistency" meant doing things as uniformly as possible (for example always call a method with the same syntax, whether the variable referencing it is the original name or an alias). -- Francois From keith.b.perry at gmail.com Tue Mar 28 15:42:29 2006 From: keith.b.perry at gmail.com (kbperry) Date: 28 Mar 2006 12:42:29 -0800 Subject: Convert Word .doc to Acrobat .pdf files In-Reply-To: <1143170241.114906.295710@e56g2000cwe.googlegroups.com> References: <1143123734.158567.97310@i39g2000cwa.googlegroups.com> <1143128817.437615.305860@u72g2000cwu.googlegroups.com> <1143150127.133624.257210@i40g2000cwc.googlegroups.com> <1143170241.114906.295710@e56g2000cwe.googlegroups.com> Message-ID: <1143578549.621123.193930@i40g2000cwc.googlegroups.com> Justin, While I was salivating when reading your post, it doesn't work for me, but I am not sure why. I keep getting an error: Titled: Adobe PDF "When you create a PostScript file you have to send the host fonts. Please go to the printer properties, "Adboe PDF Settings" page and turn OFF the option "Do not send fonts to Distiller". Keith www.301labs.com From zhong_dh at 126.com Fri Mar 3 23:12:05 2006 From: zhong_dh at 126.com (computer1) Date: 3 Mar 2006 20:12:05 -0800 Subject: scipy References: <1141376654.536347.40120@z34g2000cwc.googlegroups.com> Message-ID: <1141445525.278854.131680@i39g2000cwa.googlegroups.com> thank you very much. I have dowtnloaded it successfully. From tuvas21 at gmail.com Sat Mar 4 12:15:37 2006 From: tuvas21 at gmail.com (Tuvas) Date: 4 Mar 2006 09:15:37 -0800 Subject: Random Prime Generator/Modular Arithmetic In-Reply-To: <1141487100.450422.306010@v46g2000cwv.googlegroups.com> References: <1141487100.450422.306010@v46g2000cwv.googlegroups.com> Message-ID: <1141492537.648542.294450@u72g2000cwu.googlegroups.com> I have discoved that the mod function isn't quite right in dealing with powers, but, I'll have it fixed shortly. From mahs at telcopartners.com Mon Mar 20 14:41:25 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Mon, 20 Mar 2006 11:41:25 -0800 Subject: String comparison question In-Reply-To: References: <400BDC416E2A0042AA35DF3919BB8A5115E648@mail.mtl.proksim.com> <1142858790.888174.143470@i40g2000cwc.googlegroups.com> Message-ID: Fredrik Lundh wrote: > >>>> " hello world ".split() > ['hello', 'world'] a.split() == b.split() is a convenient test, provided you want to normalize whitespace rather than ignore it. I took the OP's requirements to mean that 'A B' == 'AB', but this is just a guess. Michael From alet at librelogiciel.com Sun Mar 19 14:49:18 2006 From: alet at librelogiciel.com (Jerome Alet) Date: Sun, 19 Mar 2006 20:49:18 +0100 Subject: [ANN] PyGNUGK v3.50 is out Message-ID: Hi there, I'm pleased to announce PyGNUGK v3.50 which is available under the terms of the GNU GPL from : http://cortex.unice.fr/~jerome/pygnugk/ PyGNUGK is a Python library which allows full control over one or more instances of the GNU GateKeeper (http://www.gnugk.org) from any Python program. PyGNUGK comes with : - The Python library. - Sample code : - A sample program which can be run : - From the command line : it prints plain text, HTML or XML reports about the list of registered endpoints and ongoing calls. - As a CGI script : When there's no user authentication, it allows the same reports as from the command line. With user authentication (i.e. Apache's .htaccess files) the HTML report contains links which can disconnect active calls or endpoints and unregister endpoints. - A test program which tests all available functions of the gatekeeper. - A Zope Product : For now it can produce HTML and XML reports, but more features will be added later. NB : the sample programs can be used directly, however for advanced needs you have to use the library. A screenshot of the CGI script taken from an earlier release is available from : http://cortex.unice.fr/~jerome/pygnugk/screenshot.png Comments are very much welcome. bye Jerome Alet From adam.deprince at gmail.com Fri Mar 24 09:52:19 2006 From: adam.deprince at gmail.com (Adam DePrince) Date: Fri, 24 Mar 2006 09:52:19 -0500 Subject: Bitwise OR? In-Reply-To: References: <1143187977.384459.225840@i40g2000cwc.googlegroups.com> <1143190128.783253.62430@i40g2000cwc.googlegroups.com> Message-ID: <1143211940.3190.19.camel@localhost.localdomain> On Fri, 2006-03-24 at 12:55 +0100, Clemens Hepper wrote: > Hello, > > I've written a little (optimized) method to get a bit-string: > > def bitstringneg(number, digits=32): > """optimized for negative numbers""" > result = "" > for a in xrange(digits): > if number & 1: > result += '1' > else: > result += '0' > number >>= 1 > return result > > def bitstringpos(number): > """optimized for positive numbers""" > result = "" > while number: > if number & 1: > result += '1' > else: > result += '0' > number >>= 1 > return result > > def bitstring(number, digits=32): > """lsb------>msb""" > result = "" > if number < 0: > return bitstringneg(number, digits) > else: > return bitstringpos(number) > > BTW: Is there something like a sizeof() method for int numbers? import struct help( strict.calcsize ) Why one bit at a time? If I rewrite your functions as: _octets = {"0":"000", "1":"001","2":"010", "3":"011", "4":"100","5":"101", "6":"110", "7":"111", "-":"" } _sign = {True:'-',False:''} def bitstring1( number ): return _sign[number<0] + ''.join( [_nibbles[d] for d in hex( number )] ).lstrip( '0' ) _nibbles = {"0":"0000", "1":"0001", "2":"0010", "3":"0011", "4":"0100", "5":"0101", "6":"0110", "7":"0111", "8":"1000", "9":"1001", "a":"1010", "b":"1011", "c":"1100", "d":"1101", "e":"1110", "f":"1111", "-":"", "x":""} def bitstring2( number ): return _sign[number<0] + ''.join( [_nibbles[d] for d in hex( number )] ).lstrip( '0' ) Now I know, my negative number sematincs are different than yours, I'll leave fixing that as an exercise to you. python2.4 -mtimeit -s 'from test_a import bitstring' 'bitstring(343890242);bitstring(-343890242)' 10000 loops, best of 3: 27.1 usec per loop python2.4 -mtimeit -s 'from test_b import bitstring1' 'bitstring1(343890242);bitstring1(-343890242)' 100000 loops, best of 3: 10.9 usec per loop python2.4 -mtimeit -s 'from test_b import bitstring2' 'bitstring2(343890242);bitstring2(-343890242)' 100000 loops, best of 3: 11.2 usec per loop And if I use a map, well, its not a statistically significant difference. def bitstring_nibblemap( number ): return _sign[number<0] + ''.join( map( _nibbles.get, hex( number ))).lstrip( '0' ) python2.4 -mtimeit -s 'from test_b import bitstring_nibblemap' 'bitstring_nibblemap(343890242);bitstring_nibblemap(-343890242)' 100000 loops, best of 3: 10.7 usec per loop Cheers - Adam From walterbyrd at iname.com Tue Mar 28 10:24:04 2006 From: walterbyrd at iname.com (walterbyrd) Date: 28 Mar 2006 07:24:04 -0800 Subject: Looking for a language/framework Message-ID: <1143559444.045808.38790@u72g2000cwu.googlegroups.com> Way back when, I got a lot of training and experience in highly structued software development. These days, I dabble with web-development, but I may become more serious. I consider php to be an abombination, the backward compatibility issues alone are reason enough to make me hate it. Rail looks promising, but it's difficult to find inexpensive hosting that supports rails. I like python much better, but I'm not certain it's as well suited for web developement. I'm not sure how th e apache module thing works. I am using shared hosting, they provide python, but I'm not sure how limited I'll be. Ideally, I would like to be able to develop a database driven web-app, in much the same manner as I could develop an ms-access app. As much as I dislike msft, I have to admit, an ms-access app can be put together quickly, without any steep learning curve. I've been looking at python web frameworks, and I'm not sure what to think. It seems like these frameworks would allow me to do a lot of work, with a small amount of code, but the learning curve seems very steep. I wouldn't even mind the steep learning curves, so much, except, it seems to me that anything developed with one framework, would not work with another. So if I changed my mind about which framework, I'd have to start all over again - re-learning everything, re-writing everything. Of course, everybody says their framework is the best. But how can I know for sure? I don't have time to try them all. From wnoise at ofb.net Thu Mar 23 12:28:56 2006 From: wnoise at ofb.net (Aaron Denney) Date: Thu, 23 Mar 2006 17:28:56 +0000 (UTC) Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1142544373.164023.50140@z34g2000cwc.googlegroups.com> <1142545215.632905.284520@j33g2000cwa.googlegroups.com> <1143109930.768224.160910@j33g2000cwa.googlegroups.com> Message-ID: On 2006-03-23, wkehowski at cox.net wrote: > The solution that would have the most utility would be one where the > elements are generated one-by-one, loop-like, so that they can be used > in the body of a loop, and to avoid the fact that even with exclusion > the cardinality of the target set EX^n could be in the millions even > with a full list of wc's, that is, a list containing at least one wc of > every length in 2..(n-1). I don't know enough Lisp, Haskell or > Qi/Prolog to know if the solutions so far can be modified to do this. > The Python program is too slow for large sets. In Haskell you can get this essentially for free, due to its laziness. -- Aaron Denney -><- From paul at boddie.org.uk Sun Mar 5 19:35:56 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 5 Mar 2006 16:35:56 -0800 Subject: Package organization: where to put 'common' modules? References: <1141419542.750676.176150@z34g2000cwc.googlegroups.com> <44098830$1_3@newspeer2.tds.net> <1141599776.392714.28350@i39g2000cwa.googlegroups.com> Message-ID: <1141605355.963705.3860@z34g2000cwc.googlegroups.com> fortepianissimo wrote: > Hm this doesn't work. Say I have the following directory structure: > > A > |--- util > | |--- foo.py > | > |--- B > |--- bar.py > > > And bar.py has this line > > from util import foo This would only work with A in sys.path/PYTHONPATH. However... > I then run > > python B/bar.py > > in directory A. Still got error > > ImportError: No module named util Yes, Python does this - it puts the directory of bar.py (B in this case) in sys.path, but not the directory in which you're sitting when you run the program from the shell (A in this case). I always get round this by running programs like this: PYTHONPATH=. python B/bar.py For me, this is a minor inconvenience since I know that ultimately the imported packages will be installed and available via site-packages. > A check of sys.path in bar.py when running from A revealed that > sys.path has A/B, not A. > > Am I missing something here? Well, I imagine that you want some kind of sys.path modification to take place, and you can certainly do this in bar.py, taking care only to do so in the "main program" section of the module - you don't usually want sys.path magic going on when just importing from the bar module. However, my advice with regard to package structure and testing would be to put common functionality either in modules below those that need such functionality in the package structure, or in a separate hierarchy in the package structure, to use absolute references to such packages (A.util.foo) rather than relative ones (util.foo or stuff soon to be permitted in Python 2.5), and to put your test programs outside the package and have them use the package code like any other piece of software. Despite the presumed benefits to the upcoming relative import support (less typing, perhaps), it's good to see that the existing import rules will be tightened up with absolute importing being enforced. Here's an example of import misbehaviour in today's Python: ---x |---y ...print "x" |---z ...import y.a # we want this to be absolute! ---y |---a ...print "y" Now try and import x.z in Python 2.4! It won't even get to printing "y". Paul From johnjsal at NOSPAMgmail.com Wed Mar 8 23:31:14 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Mar 2006 23:31:14 -0500 Subject: advice on this little script In-Reply-To: <120vb889343kd1@corp.supernews.com> References: <2bSdncqWK7aJN5LZRVn-vA@rcn.net> <120vb889343kd1@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2006-03-09, John Salerno wrote: > >> from time import sleep >> >> minutes = input('Enter the number of minutes to wait: ') >> >> for x in range(minutes): >> sleep(1.0) >> minutes -= 1 >> print minutes, 'minutes remaining.' > > for x in range(minutes,0,-1): > sleep(60.0) > print minutes, 'minutes remaining' > Nice! Cross off another line! I feel like Hemingway. :) From sybrenUSE at YOURthirdtower.com.imagination Wed Mar 29 02:24:23 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 29 Mar 2006 09:24:23 +0200 Subject: any() and all() on empty list? References: <7x3bh1x0ym.fsf@ruckus.brouhaha.com> <42qWf.18211$uX5.7574@tornado.texas.rr.com> Message-ID: Paul McGuire enlightened us with: >> That goes against the usual meaning of "all" in, say, mathematical >> logic. >> >> Usually, "for all X in S, PRED(x) is true" means: there does not >> exist X in S so that PRED(x) is false. >> > How do you get this "usually" stuff? >From its mathematical definition. > I would agree that this is usually implemented as a short-circuited > loop through the list, that breaks out at the first False value. Implementation is irrelevant when it comes to the definition of a mathematical operator. > But I would not be quick to equate "commonality of implementation" > with "meaning". Which is good. > Perhaps we should consult a more formal mathematical resource for > this. In mathematics, 'for all x in A, f(x) is True' is true when A is empty. You can either look it up on trust someone who studied mathematics (me) on 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 caleb.hattingh at gmail.com Wed Mar 29 03:15:23 2006 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 29 Mar 2006 00:15:23 -0800 Subject: Multiplying sequences with floats In-Reply-To: <9r6k22dr76r4oo65k41s4hp55gne60aiaj@4ax.com> References: <1143239583.002604.44010@v46g2000cwv.googlegroups.com> <1143580802.212165.142880@t31g2000cwb.googlegroups.com> <9r6k22dr76r4oo65k41s4hp55gne60aiaj@4ax.com> Message-ID: <1143620123.908415.50980@v46g2000cwv.googlegroups.com> Hi Dennis Sure, I get it. I do most of my work in Delphi, which is, shall we say, not lax about floating-point types. Thinking about this more, I realise my initial interest was in looking at the // operator as something new, whereas I now see it probably just wraps math.floor(); obviously then, you're going to get whatever the underlying C math library returns. As an aside, I also realised that the OP could just subclass list to make one that works with multiplications against floats: he could either floor and cast the float to int in the overloaded operator, or make a fancy system of using the fractional part of the float to duplicate the list int(floor()) times, then add just the fraction of the list that approximates most closely the decimal part of the float; this is assuming the outcome is actually meaningful for any particular problem. As I remarked to Christoph, this whole issue is actually a non-issue to me, and I don't want to give the impression I think there is a problem here; just interested in the // operator is all :) regards Caleb From bignose+hates-spam at benfinney.id.au Thu Mar 30 07:40:00 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 30 Mar 2006 22:40:00 +1000 Subject: LDTP 0.4.0 released !!! References: <442B163B0200004400005175@mcclure.wal.novell.com> <1143715621.527601.178270@j33g2000cwa.googlegroups.com> Message-ID: <87slp06r8f.fsf@rose.polar.local> "Paul Boddie" writes: > Ben Finney wrote: >> "A Nagappan" writes: >> > Welcome to the seventh issue of LDTP Newsletter! >> Nowhere in this newsletter do I see anything germane to a forum >> about Python. Why post it here, rather than somewhere more related >> to Linux or Desktops or Testing? > > Is the response "because LDTP seems to use Python extensively" good > enough? That information in the newsletter would be much more helpful, yes. Otherwise it just looks like open season for announcing any technical project to the list. Most projects have a consistent "what is this thing and why should you care" paragraph in every release announcement; this would be the place to make clear the association with the forum where it's posted. -- \ "People come up to me and say, 'Emo, do people really come up | `\ to you?'" -- Emo Philips | _o__) | Ben Finney From fortepianissimo at gmail.com Sat Mar 4 00:36:11 2006 From: fortepianissimo at gmail.com (fortepianissimo) Date: 3 Mar 2006 21:36:11 -0800 Subject: Package organization: where to put 'common' modules? In-Reply-To: <1141419542.750676.176150@z34g2000cwc.googlegroups.com> References: <1141419542.750676.176150@z34g2000cwc.googlegroups.com> Message-ID: <1141450571.897254.5760@v46g2000cwv.googlegroups.com> Ok I guess a little more "hunch" might be needed to elicit suggestions. If I chose to put foo in A, is there a way for code in B to import foo from A? Namely, is there a way to import stuff from a parent directory/package? If it's not possible without changing sys.path, what's the path of least effort - i.e., the way that requires least amount of added code (adding code to prepend sys.path in every module under B certain does the trick but requires a lot code). Thanks! From littlegreengecko at mind-enufalready-spring.com Thu Mar 2 23:22:08 2006 From: littlegreengecko at mind-enufalready-spring.com (Dick Watson) Date: Fri, 03 Mar 2006 04:22:08 GMT Subject: RPC client class? Message-ID: We have a legacy device that exposes an RPC server. We have an RPCL defininition of its interface. We want to develop an RPC client of this interface in Python that will be usable in both Win32 and open systems environments. I can find some *very* dated references to a demo/rpc.py, but I can't find such a file on my Win Python install. There is an rpc.py in idle, but it doesn't seem to be a general purpose implementation. (I can find **lots** of references to xmlrpc.py, but the server predates all of this neato XML stuff. I also found the "Stackless" rpc.py; it wants to modify base Python. I'd rather not diverge from the stock Python.) Is there a Python module suitable for RPC client creation? Where? Why is this not a standard class? Are we nuts to pursue this course? From cito at online.de Wed Mar 15 17:48:24 2006 From: cito at online.de (Christoph Zwerschke) Date: Wed, 15 Mar 2006 23:48:24 +0100 Subject: Python Debugger / IDE ?? In-Reply-To: <1142457652.412231.26050@v46g2000cwv.googlegroups.com> References: <1142357338.313046.139060@i39g2000cwa.googlegroups.com> <1142457652.412231.26050@v46g2000cwv.googlegroups.com> Message-ID: krypto.wizard at gmail.com wrote: > I like the Pyscripter, is there any Linux version or something of it. Sorry, I forgot to mention that there is a snag in it. Since PyScripter is based on Python for Delphi, it is available for Windows only. -- Christoph From tim at pollenation.net Thu Mar 16 08:35:15 2006 From: tim at pollenation.net (Tim Parkin) Date: Thu, 16 Mar 2006 13:35:15 +0000 Subject: Cheese Shop: some history for the new-comers In-Reply-To: <20060316061955.4065c03a@samwise.anansi> References: <44126523$0$1016$afc38c87@news.optusnet.com.au> <20060316061955.4065c03a@samwise.anansi> Message-ID: <44196993.9030505@pollenation.net> Terry Hancock wrote: > On Tue, 14 Mar 2006 13:22:09 -0700 > Steven Bethard wrote: > >>A.M. Kuchling wrote: >> >>>On Sun, 12 Mar 2006 10:25:19 +0100, >>> Fredrik Lundh wrote: >>> >>>>and while you're at it, change "python-dev" to >>> >>>"developers" and > "psf" to "foundation" (or use a title >>>on that link). >>> >>>I've changed the PSF link, but am not sure what to do >>>about the python-dev link. As others have noted, >>>"Developers" is ambiguous about whether it's for people >>>who develop in Python or who develop Python itself. >>>"Core Development"? (Used on both perl.org and tcl.tk, >>>so maybe this is the best option.) "Development Team"? >> >>+1 on Core Development. It's still ambiguous, but less >>so. And I can't think of anything better. ;) > > > Since I just said almost that independently on an earlier > thread, I guess that makes me +1 on "Core Development" (or > "Core Developers") myself. > Sold to the man in the blue hat!! It's on the server now... Tim Parkin From mtobis at gmail.com Fri Mar 24 18:41:02 2006 From: mtobis at gmail.com (Michael Tobis) Date: 24 Mar 2006 15:41:02 -0800 Subject: a problem to solve In-Reply-To: <1143237995.862980.135710@i40g2000cwc.googlegroups.com> References: <5oiUf.1818$No6.41433@news.tufts.edu> <1143071664.377833.136660@z34g2000cwc.googlegroups.com> <1143232745.363162.53810@j33g2000cwa.googlegroups.com> <1143237995.862980.135710@i40g2000cwc.googlegroups.com> Message-ID: <1143243662.182759.230130@e56g2000cwe.googlegroups.com> Yeah, I misread the question, but the gist of my query remains. > The odds are 100% if there is at least one solution. Let's not get too philosophical. My question was whether there was an a priori reason for believing that there is a solution. > You want permutations with replacement, so there are 8**4 = 4096 Agreed. My mistake. >> These will turn on 15 lights in each set of 20, of which the number of >> possibilities is C(15,20)**4 = 57779667567968256L > No, there are only 8 possible patterns on each panel. > Not every possible 15 lamp pattern is realized Right, but that is exactly my point. This is the number of possible selections of 15 out of 20 made four times. Any attempt will be a member of that space. Then the probability of hitting a solution at random is the ratio of solutions to that space. So I think my chance of success on a sinlge selection, assuming random design of the switch banks, is correct: 1.9e-05 My error gave me the wrong multiplier. It's 4096 rather than 1820. So now I'm goinq with a 7.79% chance of randomly setting up the problem to yield a solution. Still seems somwhat unlikely that there would be a solution unless the problem were set up in advance. (homework? a puzzle book?), I am just wondering where the puzzle came from. Was there more than one solution? mt From grflanagan at yahoo.co.uk Sun Mar 5 15:14:53 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 5 Mar 2006 12:14:53 -0800 Subject: Separating elements from a list according to preceding element In-Reply-To: <1141589424.031872.309820@j33g2000cwa.googlegroups.com> References: <1141587629.918414.245530@t39g2000cwt.googlegroups.com> <1141589424.031872.309820@j33g2000cwa.googlegroups.com> Message-ID: <1141589693.568666.323470@e56g2000cwe.googlegroups.com> Gerard Flanagan wrote: > Rob Cowie wrote: > > I'm having a bit of trouble with this so any help would be gratefully > > recieved... > > > > After splitting up a url I have a string of the form > > 'tag1+tag2+tag3-tag4', or '-tag1-tag2' etc. The first tag will only be > > preceeded by an operator if it is a '-', if it is preceded by nothing, > > '+' is to be assumed. > > > > Using re.split, I can generate a list that looks thus: > > ['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4'] > > > > I wish to derive two lists - each containing either tags to be > > included, or tags to be excluded. My idea was to take an element, > > examine what element precedes it and accordingly, insert it into the > > relevant list. However, I have not been successful. > > > > Is there a better way that I have not considered? If this method is > > suitable, how might I implement it? > > > > Thanks all, > > > > Rob Cowie > > a = [ '+', 'tag1', '+', 'tag2', '-', 'tag3', '+', 'tag4' ] > > import itertools > > b = list(itertools.islice(a,0,8,2)) > c = list(itertools.islice(a,1,8,2)) > > result1 = [x[1] for x in itertools.izip(b,c) if x[0] == '+'] > result2 = [x[1] for x in itertools.izip(b,c) if x[0] == '-'] > > print > print result1 > print result2 > > > Gerard '8' is the length of 'a' (len(a)) From No.Spam at Spam.none Wed Mar 29 17:34:13 2006 From: No.Spam at Spam.none (I. Myself) Date: Wed, 29 Mar 2006 22:34:13 GMT Subject: GUI in python In-Reply-To: <1143670803.148098.21940@z34g2000cwc.googlegroups.com> References: <1143670803.148098.21940@z34g2000cwc.googlegroups.com> Message-ID: diffuser78 at gmail.com wrote: > Hi, > > I am a python newbie and have used it for about a month. I want to make > a simple GUI app in Python ( I take input form user and do processing > and show results). > > Which gui package is good for me. I need to do it quick and I would not > want a long learning curve. > > I was taking look at wxPython, pyGTK etc. > > > Please suggest me the most simplest and easiest one as I dont need > super cool aesthetics just a plain simple GUI app. > > Thanks > > I've had very good results with Tkinter, which is the standard Python GUI system. On windows, it comes with the standard download. With linux you have to download it separately. Mitchell Timin -- I'm proud of http://ANNEvolve.sourceforge.net. I'm currently working on a major update of the SailChallenge package. If you want to write software, or articles, or do testing 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 wkehowski at cox.net Thu Mar 16 21:18:10 2006 From: wkehowski at cox.net (wkehowski at cox.net) Date: 16 Mar 2006 18:18:10 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: <1142559980.525680.282250@u72g2000cwu.googlegroups.com> References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <8764medlhm.fsf@qrnik.zagroda> <1142556358.098924.59180@e56g2000cwe.googlegroups.com> <1142559980.525680.282250@u72g2000cwu.googlegroups.com> Message-ID: <1142561890.772349.17260@z34g2000cwc.googlegroups.com> -- The states are lists of regular expressions -- where [a,b,..] means match a or b or... I haven't run or studied your program yet myself but what I had in mind was that the list of wc's are *all* to be excluded, so the list [wc1..wcn] is to correspond generating all tuples matching not(wc1 and .. and wcn). Maybe you're already doing that. The wc's themselves could be logical statements among the 'primitive' wc's. That's why I named it the 'wildcard exclusion problem'. It's a lot easier to specify a list of simpler wc's than create a long logical expression. Thanks to all who are making this an interesting thread. From ianare at gmail.com Wed Mar 8 02:12:14 2006 From: ianare at gmail.com (=?iso-8859-1?B?aWFuYXLp?=) Date: 7 Mar 2006 23:12:14 -0800 Subject: suse linux 10 and wx.listctrl display issues In-Reply-To: <1141799391.412666.160650@j52g2000cwj.googlegroups.com> References: <1141799391.412666.160650@j52g2000cwj.googlegroups.com> Message-ID: <1141801934.075608.68840@j33g2000cwa.googlegroups.com> hum finally did find some SuSE specific RPM's through yast by setting the media directory to mirros.kernel.org. Cool. But still the same thing happens... From aleaxit at yahoo.com Sun Mar 5 11:16:12 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 5 Mar 2006 08:16:12 -0800 Subject: Why I chose Python over Ruby References: <1141573450.667103.8930@z34g2000cwc.googlegroups.com> Message-ID: <1hbpvkf.1lnu9vjfdg3j2N%aleaxit@yahoo.com> Francois wrote: > Since I did a lot of work in Scheme, rigor and consistency are most > important to me, and Python certainly meets this requirement. It does pretty well, with some tempering of pragmatism -- but, to play devil's advocate, Ruby isn't far in this respect. In either case, you will find more rigor and consistency in good languages of a more academic bent, such as Haskell, but will surely find a lot in either Ruby or Python. The trick about distinguishing a name's exact nature based on whether the compiler sees an assignment to that name in some part of code is found in both languages, albeit in different ways. In Ruby, as you've pointed out, it's the heuristic used to disambiguate local variable access from zero-argument method calls, and the "part of code" is the function up to the point of access. In Python, it's used to disambiguate local from global or free variables, and the "part of code" is the body of the whole function (Ruby does not need to make this latter distinction because it strops global names with a leading sigil -- $a is always the global variable a, just like @a is always the instance attribute a, which we'd write self.a in Python). Another subtle case in Ruby is whether an assignment such as a=23 _within a block_ is meant to be local to the block or meant to rebind local name 'a' within the enclosing function; again, the heuristic is similar, depending only on whether the compiler had seen another assignment to a before it saw the block (Python forbids the rebinding of variables coming from an enclosing but non-global scope, to avoid facing this issue). All in all, Python is more likely with these heuristics to respect the principles (from the "zen of python", import this at an interactive prompt): in face of ambiguity, refuse the temptation to guess; errors should not pass silently, unless explicitly silenced. I.e., any Python code which accidentally runs afoul of these heuristics is likely to raise an exception, alerting you to the situation. Ruby strives rather for a "do what I mean" ethos, and obviously some people prefer that. I also share your preference for a single namespace for callable and non-callable values, as in Python (and Scheme, Lisp, C++, ...), rather than disjoint namespaces as in Ruby (and Smalltalk), but I do not see it as a question of rigor and consistency at all -- e.g., I do not perceive Smalltalk as less rigorous or consistent than C++, on the contrary. So, I agree with your choice, and I think I understand your motivations, but I do not entirely share your motivations, personally speaking. Alex From fredrik at pythonware.com Wed Mar 22 03:09:09 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Mar 2006 09:09:09 +0100 Subject: TypeError coercing to Unicode with field read from XML file References: <1142991689.520777.28860@v46g2000cwv.googlegroups.com> Message-ID: Randall Parker wrote: > I'm probably doing something dumb as I've never done XML in Python > before. Any ideas what? using minidom ? ;-) if you're not wedded to minidom, there are alternatives that are easier to use for things like this. here's an ElementTree version of your code: ConfigTree = ET.parse(TestSettingsStore.ConfigFileName) # ConfigTree represents the TargetSocketSettings root element TargetIPAddr = tree.findtext("TargetIPAddr") TargetIPPort = tree.findtext("TargetIPPort") if TargetIPAddr and TargetIPPort: StillNeedSettings = False TestSettingsStore.SettingsDictionary["TargetIPAddr"] = TargetIPAddr TestSettingsStore.SettingsDictionary["TargetIPPort"] = TargetIPPort where ET is set by something like: try: import xml.etree.ElementTree as ET # Python 2.5 except ImportError: # http://effbot.org/zone/element-index.htm import elementtree.ElementTree as ET if you don't want to ship the entire ElementTree library with your app, you can just add the ElementTree.py module somewhere, and do e.g. import myapp.utils.ElementTree as ET ::: if you plan to grab more stuff from XML files, you might wish to apply the DRY principle (google it!), and use a little helper to copy the variables from the XML file to your dictionary: def getconfig(settings, elem, keys): d = {} for key in keys: value = elem.findtext(key) if not value: return False d[key] = value # only update the settings dict if all keys were present settings.update(d) return True if getconfig( TestSettingsStore.SettingsDictionary, ConfigTree, ("TargetIPAddr", "TargetIPPortX")): StillNeedSettings = False From max at alcyone.com Sun Mar 5 18:59:14 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 05 Mar 2006 15:59:14 -0800 Subject: Opening files without closing them In-Reply-To: References: <1141598002.402189.275520@i40g2000cwc.googlegroups.com> Message-ID: Robert Kern wrote: >> I usually use: >> >> try: >> f = open(file) >> contents = f.read() >> finally: >> f.close() >> >> But now I am wondering if that is the same thing. Which method would >> you rather use? Why? > > Just keep doing what you are doing, please. Note quite. The assignment of the resources to its variable needs to be done before the try: f = open(file) try: contents = f.read() finally: f.close() -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Who, my friend, can scale heaven? -- _Gilgamesh_, ca. 3rd C. BC From email at christoph-haas.de Sat Mar 25 15:18:58 2006 From: email at christoph-haas.de (Christoph Haas) Date: Sat, 25 Mar 2006 21:18:58 +0100 Subject: a somewhat off-topic question about linux In-Reply-To: <_oedne4wPJ9DPrjZnZ2dnUVZ_tWdnZ2d@rcn.net> References: <_oedne4wPJ9DPrjZnZ2dnUVZ_tWdnZ2d@rcn.net> Message-ID: <20060325201858.GB14511@aldi.workaround.org> On Sat, Mar 25, 2006 at 03:09:53PM -0500, John Salerno wrote: > I'm interested in trying out Linux, probably Ubuntu, but I was wondering > which distribution you guys like to use (because it's a pain trying to > decide!) and you guys are smart. We had this discussion a couple of time during the last months already. :) I believe the most frequently recommended distribution was Ubuntu (or Debian which Ubuntu is based upon). > And to keep it Python related, I'll also ask, is there anything special > I need to know about using Python on Linux? Do any things change, or can > it be used just as I use it on Windows? Some issues are platform-dependant. You will not be able to read the registry or start a Microdoze-based program of course. Otherwise most parts of Python are working the same way unless the documentation tells otherwise in certain details. Christoph (Hoping to prevent a huge thread discussing pros/cons of distributions) -- ~ ~ ".signature" [Modified] 1 line --100%-- 1,48 All From dimitri.pater at gmail.com Mon Mar 20 18:42:39 2006 From: dimitri.pater at gmail.com (dimitri pater) Date: Tue, 21 Mar 2006 00:42:39 +0100 Subject: New-style Python icons In-Reply-To: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> Message-ID: wow, good work! thanks, Dimitri On 20 Mar 2006 08:56:59 -0800, and-google at doxdesk.com < and-google at doxdesk.com> wrote: > > Personally, I *like* the new website look, and I'm glad to see Python > having a proper logo at last! > > I've taken the opportunity to knock up some icons using it, finally > banishing the poor old standard-VGA-palette snake from my desktop. If > you like, you can grab them from: > > http://www.doxdesk.com/img/software/py/icons.zip > > in .ICO format for Windows - containing all resolutions/depths up to > and including Windows Vista's crazy new enormo-icons. Also contains the > vector graphics source file in Xara format. You can also see a preview > here: > > http://www.doxdesk.com/img/software/py/icons.png > > -- > And Clover > mailto:and at doxdesk.com > http://www.doxdesk.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- ---- "All truth passes through three stages. First, it is ridiculed. Second, it is violently opposed. Third, it is accepted as being self-evident." ~Arthur Schopenhauer ---- Please visit dimitri's website: www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at ucla.edu Fri Mar 3 18:44:23 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 03 Mar 2006 15:44:23 -0800 Subject: How to except the unexpected? In-Reply-To: References: Message-ID: Rene Pijlman wrote: > One of the things I dislike about Java is the need to declare exceptions > as part of an interface or class definition. But perhaps Java got this > right... > > I've writen an application that uses urllib2, urlparse, robotparser and > some other modules in the battery pack. One day my app failed with an > urllib2.HTTPError. So I catch that. But then I get a urllib2.URLError, so > I catch that too. The next day, it encounters a urllib2.HTTPError, then a > IOError, a socket.timeout, httplib.InvalidURL,... > > How do you program robustly with these modules throwing all those > different (and sometimes undocumented) exceptions at you? > > A catchall seems like a bad idea, since it also catches AttributeErrors > and other bugs in the program. > The relevant lines of urllib2, for example, look as such: class URLError(IOError): class HTTPError(URLError, addinfourl): class GopherError(URLError): This suggests that catching URLError should have caught your HTTPError, so you might have the chronology backwards above. E.g.: py> class BobError(Exception): pass ... py> class CarolError(BobError): pass ... py> try: ... raise CarolError ... except BobError: ... print 'got it' ... got it Now, % cat httplib.py | grep -e '^\s*class' produces the following at one point in its output: class HTTPException(Exception): class NotConnected(HTTPException): class InvalidURL(HTTPException): class UnknownProtocol(HTTPException): class UnknownTransferEncoding(HTTPException): class UnimplementedFileMode(HTTPException): class IncompleteRead(HTTPException): class ImproperConnectionState(HTTPException): class CannotSendRequest(ImproperConnectionState): class CannotSendHeader(ImproperConnectionState): class ResponseNotReady(ImproperConnectionState): class BadStatusLine(HTTPException): Which suggests that "try: except HTTPException:" will be specific enough as a catchall for this module. The following, then, should catch everything you mentioned except the socket timeout: try: whatever() except URLError, HTTPException: alternative() But it seems to me that working with the internet as you are doing is fraught with peril anyway. James From kay.schluehr at gmx.net Sat Mar 11 18:05:56 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 11 Mar 2006 15:05:56 -0800 Subject: How to refer to the function object itself in the function per se? In-Reply-To: <1142116513.937950.169380@i40g2000cwc.googlegroups.com> References: <1142108608.559879.45560@i39g2000cwa.googlegroups.com> <1142112883.126132.301290@j52g2000cwj.googlegroups.com> <1142116513.937950.169380@i40g2000cwc.googlegroups.com> Message-ID: <1142118356.882341.50120@z34g2000cwc.googlegroups.com> Sullivan WxPyQtKinter wrote: > I am sorry but you misunderstood my idea. > What I want is a generalized method to print out the function name, or > refer to the name of a function. If I use f.__name__, I think I should > just use print "f" to save my keyboard. What I expect is using a > method, or attribute, or another function to get the name of a > function. Sorry, if the example was misleading. Here is a better one: def f(g): print g.__name__ >>> f(f) f The __name__ attribute of f is constant and it doesn't matter whether you pass f around or create aliases: >>> x = f >>> x.__name__ f x refers still to the function object f. Therefore the __name__ attribute does not return "x" but "f". You will always print the right function name not the name of the local variable. Kay From programmer.py at gmail.com Fri Mar 10 16:39:32 2006 From: programmer.py at gmail.com (programmer.py at gmail.com) Date: 10 Mar 2006 13:39:32 -0800 Subject: epydoc help (putting XML in docstrings) In-Reply-To: References: <1142023769.899027.114920@j33g2000cwa.googlegroups.com> Message-ID: <1142026772.811057.32450@p10g2000cwp.googlegroups.com> Doh. That was too easy. Thanks! jw From hancock at anansispaceworks.com Sat Mar 4 12:52:59 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 4 Mar 2006 11:52:59 -0600 Subject: Easy immutability in python? Message-ID: <20060304115259.2e426ca8@samwise.anansi> Is there an *easy* way to make an object immutable in python? Or perhaps I should say "one obvious way to do it"? Oughtn't there to be one? I've found a thread on how to do this[1], which essentially says something like "redefine __setattr__, __delattr__, __hash__, __eq__, __setitem__, delitem__ ... and probably some other stuff too". [1] Yet, what you have to do is pretty mechanical (e.g. all the mutators have to raise NotImplementedError and the hashes and comparisons seem like they have obvious defaults). Given that I have some kind of container, like an overloaded list, and I just say "oh, I need that to be immutable, like a tuple" -- it would be nice to just be able to declare it so. I just want this for QA purposes -- I have a pretty complex system, and I want the programmer to be warned when he accidentally tries to change an immutable enumeration or redefine a symbol. I know a (hard and error-prone) way to do it, but I'm thinking there must be a "smart" way to do it. Is there some way to do that with, e.g. decorators? (I haven't really figured out why I should want decorators, is this a use case?). Or maybe I should make an "Immutable" class, and just inherit from it last so it overloads everything else with the null interfaces? -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From acm at muc.de Thu Mar 9 04:06:50 2006 From: acm at muc.de (Alan Mackenzie) Date: Thu, 9 Mar 2006 09:06:50 +0000 Subject: license preamble template References: <1133844932.007824.26780@g43g2000cwa.googlegroups.com> <1134780763.066592.45390@g49g2000cwa.googlegroups.com> <1135405908.381150.133190@o13g2000cwo.googlegroups.com> <1136236586.734775.212440@f14g2000cwb.googlegroups.com> <1137784561.589887.58380@o13g2000cwo.googlegroups.com> <1139909629.798938.284160@g47g2000cwa.googlegroups.com> <1141496471.387640.118020@j33g2000cwa.googlegroups.com> Message-ID: Xah Lee wrote on 4 Mar 2006 10:21:11 -0800: > I noticed, that in just about all emacs programs on the web (elisp > code), it comes with this template text as its preamble: [ .... ] > ;; This program is distributed in the hope that it will be useful, but > ;; WITHOUT ANY WARRANTY; without even the implied warranty of > ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU > ;; General Public License for more details. [ .... ] > Concerned parties and the FSF foundation, please remove the middle > section of this template. That section is mainly for lawyers, for > programers to protect themselves in the context of modern society's law > system. Legally speaking, that section is redundant because it is in > the GNU General Public License itself. That section is there to draw people's attention to the lack of a warranty, to cause them to contrast it with the "warranty" offered by non-free software, which typically is restricted to replacing the distribution CD if it can't be read. > The effect of that section in a license summary is fueling the habit > and sanction of irresponsible programing we see all around us. My impression is that irresponsible programming tends to come with a guarantee to replace the distribution CD if it can't be read. > In place of that section, i'd propose replacing it with the following > gist: > ??This program is distributed in the hope that it will be useful. The > author(s) has responsibly produced it, and will take reasonable > responsibilities with regards to the program's intended purpose and > workability. For legal aspects of WARRANTY, please see the GNU General > Public License for more details.?? Nah, that's too defensive and wooly. If you get an Email from a stranger that says "checked virus-free by ....", would you believe that? No? Then why would you believe a programmer who feels he has to assert he has done his work "responsibly", whatever that might mean? It's legally dubious, and wouldn't inspire any confidence whatsoever. Responsibility is shown by actions and results, not promises. [ .... ] > Xah -- Alan Mackenzie (Munich, Germany) Email: aacm at muuc.dee; to decode, wherever there is a repeated letter (like "aa"), remove half of them (leaving, say, "a"). From salvatore.didio at wanadoo.fr Sun Mar 26 17:17:26 2006 From: salvatore.didio at wanadoo.fr (Salvatore) Date: 26 Mar 2006 14:17:26 -0800 Subject: Python types In-Reply-To: <4426f7a4$0$27969$626a54ce@news.free.fr> References: <1143230541.717833.35440@e56g2000cwe.googlegroups.com> <44247674$0$25385$636a55ce@news.free.fr> <1143306481.966061.26300@t31g2000cwb.googlegroups.com> <4426f7a4$0$27969$626a54ce@news.free.fr> Message-ID: <1143411446.212407.221560@i39g2000cwa.googlegroups.com> Thank's Bruno. From http Wed Mar 1 23:48:56 2006 From: http (Paul Rubin) Date: 01 Mar 2006 20:48:56 -0800 Subject: PEP 354: Enumerations in Python References: <87accdplbj.fsf@rose.polar.local> <1141019214.153904.115220@j33g2000cwa.googlegroups.com> <877j7gz53k.fsf@rose.polar.local> <7xd5h8jnk1.fsf@ruckus.brouhaha.com> <87hd6j3s51.fsf@rose.polar.local> <7xhd6ilxk2.fsf@ruckus.brouhaha.com> <87k6bdsg91.fsf@rose.polar.local> Message-ID: <7x3bi15u4n.fsf@ruckus.brouhaha.com> Ben Finney writes: > > I don't know about this. It makes athlon64_instructions a > > completely separate enum from pentium_instructions. It could be > > that athlon64_instructions.add should be the same as > > pentium_instructions.add . > > If you want the members of two distinct collections to have a > meaningful relationship, you don't want enumerations. The basic > promise of the specified enumeration interface is that every member of > an enumeration is a unique value. The premise is that they're not necessarily distinct (disjoint) collections; one of them has been explicitly created as a superset of the other. From brian at rkspeed-rugby.dk Fri Mar 10 02:55:13 2006 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: Fri, 10 Mar 2006 08:55:13 +0100 Subject: Simple questions on use of objects (probably faq) References: <4410451a$0$70318$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: Michael writes: > Based on the code that runs, you want* this: > > [(y[x+1].x-y[x].x) for x in range(len(y)-1) ] Yes. > Since personally I find that a lot clearer than: > > map(float.__sub__, [X.x for X in y[1:]], [X.x for X in y[:-1] ]) Me too. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk From plahey at alumni.caltech.edu Sat Mar 11 16:50:42 2006 From: plahey at alumni.caltech.edu (plahey at alumni.caltech.edu) Date: 11 Mar 2006 13:50:42 -0800 Subject: API/C memory mananegemnt problem In-Reply-To: References: <200603100919.29946.fumana@mi.iasf.cnr.it> <1142056998.489727.168570@e56g2000cwe.googlegroups.com> <1142060403.333298.86840@e56g2000cwe.googlegroups.com> <1hc18a8.1u0a6cx14wyhuhN%aleaxit@yahoo.com> Message-ID: <1142113842.101525.317610@i40g2000cwc.googlegroups.com> This exactly what I was thinking. Are we wrong Alex? From lucmult at gmail.com Wed Mar 29 10:57:16 2006 From: lucmult at gmail.com (lucmult at gmail.com) Date: 29 Mar 2006 07:57:16 -0800 Subject: excel application In-Reply-To: <1143644666.914943.121390@i40g2000cwc.googlegroups.com> References: <1143644666.914943.121390@i40g2000cwc.googlegroups.com> Message-ID: <1143647835.963572.270710@u72g2000cwu.googlegroups.com> Hi Luca, The words xlDiagonalDown e xlNone are Excel constants and don't are in the Local NameSpace use these values: xlNone = -4142 xlDiagonalDown = 5 Then the last line stay like that """ packing.ActiveSheet.Selection.Borders(5).LineStyle = -4142 # Excel Constants: xlNone = -4142 xlDiagonalDown = 5 """ When use the integer values in your code remeber to comment the significant of these values, to a future corrections :) [], Luciano Pacheco From martin at v.loewis.de Fri Mar 17 14:08:16 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 17 Mar 2006 20:08:16 +0100 Subject: Python vs. Java gzip performance In-Reply-To: <1142610889.512781.69650@j33g2000cwa.googlegroups.com> References: <1142610889.512781.69650@j33g2000cwa.googlegroups.com> Message-ID: <441B0920.4060106@v.loewis.de> Bill wrote: > The Java version of this code is roughly 2x-3x faster than the Python > version. I can get around this problem by replacing the Python > GzipFile object with a os.popen call to gzcat, but then I sacrifice > portability. Is there something that can be improved in the Python > version? Don't use readline/readlines. Instead, read in larger chunks, and break it into lines yourself. For example, if you think the entire file should fit into memory, read it at once. If that helps, try editing gzip.py to incorporate that approach. Regards, Martin From trentm at ActiveState.com Fri Mar 31 19:40:18 2006 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 31 Mar 2006 16:40:18 -0800 Subject: Exception handling....dumb question? In-Reply-To: <1143849093.457940.294150@g10g2000cwb.googlegroups.com> References: <1143849093.457940.294150@g10g2000cwb.googlegroups.com> Message-ID: <20060401004018.GE12519@activestate.com> [kbperry wrote] > In Python, > When using the default except (like following) > > try: > some code that might blow up > > except: > print "some error message" >>> try: ... 1/0 ... except: ... import traceback ... traceback.print_exc() ... Traceback (most recent call last): File "", line 2, in ? ZeroDivisionError: integer division or modulo by zero Or, if you are using the logging module: >>> import logging >>> log = logging.getLogger("myscript") >>> logging.basicConfig() >>> >>> try: ... 1/0 ... except: ... log.exception("whoa!") ... ERROR:myscript:whoa! Traceback (most recent call last): File "", line 2, in ? ZeroDivisionError: integer division or modulo by zero Cheers, Trent -- Trent Mick TrentM at ActiveState.com From grahamd at dscpl.com.au Wed Mar 29 05:11:10 2006 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 29 Mar 2006 02:11:10 -0800 Subject: mod_python bytecompiling References: <1143625503.312591.31000@i40g2000cwc.googlegroups.com> Message-ID: <1143627070.805953.47730@u72g2000cwu.googlegroups.com> Fredrik Lundh wrote: > "mneagul" wrote: > > > I am writing a small program using mod_python publisher extension. I > > have created several python files and imported them in a `main' file. > > How can I stop mod_python to byte compile the files? I want to make > > changes to the files and see result imediately! > > > > In the current setup only the changes to the `main' file are applied > > imediately. I is nearly imposible to develop an application this way. > > > > I want to mention that I'm a newby to mod_python. > > the FAQ has the answer: > > http://www.modpython.org/FAQ/faqw.py?req=show&file=faq03.001.htp > "Q. My module imports other modules - how do I reload those?" > > (another approach, used by several frameworks, is to use a stand-alone > test server for development, and mod_python for deployment) Simply using apache.import_module() is not going to necessarily help at the moment as it has various problems and shortcomings. One of them is that it does not check multiple levels of dependencies between modules. Thus simply replacing global imports in a module with a call to apache.import_module() will not help. For a full list of problems and issues with the mod_python module importer see: http://www.dscpl.com.au/articles/modpython-003.html There is a new module importer being tested with mod_python 3.3 which will hopefully eliminate the major problems. Highly recommend that original poster get onto the mod_python mailing list to discuss what he can do in the interim. Graham From juho.schultz at helsinki.fi Tue Mar 7 10:14:06 2006 From: juho.schultz at helsinki.fi (Juho Schultz) Date: Tue, 07 Mar 2006 17:14:06 +0200 Subject: What version of python is running a script In-Reply-To: References: Message-ID: Fernando Rodr?guez wrote: > > Hi, > > How can my script tell which version of python is running it? > > Thanks > > import sys # examine these variables sys.version_info sys.version From rrr at ronadam.com Thu Mar 30 06:09:13 2006 From: rrr at ronadam.com (Ron Adam) Date: Thu, 30 Mar 2006 05:09:13 -0600 Subject: any() and all() on empty list? In-Reply-To: <4%OWf.9490$Aa1.5525@dukeread05> References: <442B9AF7.2010407@REMOVEMEcyber.com.au> <7xu09gicko.fsf@ruckus.brouhaha.com> <442BAAA5.8010009@REMOVEMEcyber.com.au> <4%OWf.9490$Aa1.5525@dukeread05> Message-ID: <02PWf.9537$Aa1.6583@dukeread05> Ron Adam wrote: > > hasall(S, True, lambda n: n=42) > That was suppose to be: hasall(S, True, lambda n: n==42) From enleverlesX.XmcX at XmclaveauX.com Thu Mar 16 07:31:25 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Thu, 16 Mar 2006 13:31:25 +0100 Subject: MS word document generator References: <1142413907.226088.190740@j33g2000cwa.googlegroups.com> <121gblgb57p39e9@corp.supernews.com> <1142449946.532024.171530@z34g2000cwc.googlegroups.com> Message-ID: <44195b79$0$29204$8fcfb975@news.wanadoo.fr> Hi! Yes, I have an idea. But... I has no time, actually. Perhaps in 2 or 3 weeks... Sorry. Michel Claveau From konrad.hinsen at laposte.net Mon Mar 20 11:30:47 2006 From: konrad.hinsen at laposte.net (Konrad Hinsen) Date: Mon, 20 Mar 2006 17:30:47 +0100 Subject: MPI implementations In-Reply-To: <5f56302b0603172004w11f69723hb231b1cdfe97b90f@mail.gmail.com> References: <5f56302b0603172004w11f69723hb231b1cdfe97b90f@mail.gmail.com> Message-ID: On Mar 18, 2006, at 5:04, Daniel Nogradi wrote: > I plan to use python parallel and -- fortunately or unfortunately -- > there are several implementations. At the moment I'm aware of > > http://datamining.anu.edu.au/~ole/pypar/ > http://pympi.sourceforge.net/ > http://www.fysik.dtu.dk/~schiotz/comp/PythonAndSwig/pythonMPI.html > > and wondered if anyone had experience with any of them. Pros, cons? > Did anyone try more than one? Add this one: http://dirac.cnrs-orleans.fr/ScientificPython/ScientificPythonManual/ Scientific_27.html and unless you are 100% convinced that MPI is the interface you want to use, also check out this: http://dirac.cnrs-orleans.fr/ScientificPython/BSP_Tutorial.pdf PyPar and pyMPI are both high-level interfaces to MPI, i.e. they propose an MPI-like message passing interface with the main added value being communication of arbitrary Python objects. My own MPI interface in ScientificPython is more low-level, since it handles only strings and arrays. Its strong point is its C interface, which makes it possible to write parallelized mixed C-Python code and to integrate parallelized C libraries into Python projects. My BSP interface (the second link) is what I personally consider the most convenient interface for parallel programming in Python. It is built on the BSP (Bulk Synchronous Processing) model that works at a higher level than message passing: the programmer does not have to worry about synchronization, which is a major source of hard-to-track- down bugs. Konrad. -- --------------------------------------------------------------------- Konrad Hinsen Laboratoire L?on Brillouin, CEA Saclay, 91191 Gif-sur-Yvette Cedex, France Tel.: +33-1 69 08 79 25 Fax: +33-1 69 08 82 61 E-Mail: konrad.hinsen at cea.fr --------------------------------------------------------------------- From johnjsal at NOSPAMgmail.com Mon Mar 27 18:15:20 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 27 Mar 2006 18:15:20 -0500 Subject: problems with looping, i suppose In-Reply-To: <1143487276.684171.220440@e56g2000cwe.googlegroups.com> References: <1143486277.480720.148040@t31g2000cwb.googlegroups.com> <1143487276.684171.220440@e56g2000cwe.googlegroups.com> Message-ID: <4428726b$0$11643$c3e8da3@news.astraweb.com> akameswaran at gmail.com wrote: > Ok I felt a little bad for my quick answer, these just seem like > homework problems. NP. I appreciate your help. These are just little exercises I found online, just to give me a reason to use Python. :) From johnjsal at NOSPAMgmail.com Wed Mar 8 14:00:44 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Mar 2006 19:00:44 GMT Subject: why no block comments in Python? In-Reply-To: <1141843360.140692.44180@i39g2000cwa.googlegroups.com> References: <_MCPf.1749$No6.40293@news.tufts.edu> <1141843360.140692.44180@i39g2000cwa.googlegroups.com> Message-ID: Warby wrote: > The danger with block comments is that there is no way to tell that the > code you're looking at has been commented out unless you can see the > start or end of the comment block. If you have a modern editor, it > probably changes the color of all commented out code to eliminate > confusion. But if you have a primitive editor it does not. That makes sense. If you have a modern editor, you don't need blocks. If you don't have one, blocks don't help. :) From enleverlesX.XmcX at XmclaveauX.com Fri Mar 31 09:03:18 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Fri, 31 Mar 2006 16:03:18 +0200 Subject: How to determine COM objects/functions References: Message-ID: <442d4029$0$21277$8fcfb975@news.wanadoo.fr> Hi! COM browsers, Makepy, and other tools run only for statics COM servers. For dynamic-COM-servers, there are ... only ... documentation. @-salutations Michel Claveau From sullivanz.pku at gmail.com Mon Mar 27 12:24:59 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 27 Mar 2006 09:24:59 -0800 Subject: CGI redirection: let us discuss it further Message-ID: <1143480299.024145.272600@u72g2000cwu.googlegroups.com> I am now programming python scripts for CGI environment. The redirection has been discussed in this forum for over one hundred times. I have seen most of them, but still have some questions: 1. Are there any method (in python of course) to redirect to a web page without causing a "Back" button trap(ie, when user click the back button on their web browser, they are redirect to their current page, while their hope is probably to go back to the last page they have seen, rather than the redirection page with a "Location: url" head and blank content.)? 2. Are there any method to use relative path, rather than full absolute URI path in "Location: url"? It is very essential for later transplant work, e.g.,transplant a folder of cgi scripts from one web server to another, with different URL. Thank you. From jeff at schwabcenter.com Thu Mar 16 16:39:26 2006 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Thu, 16 Mar 2006 21:39:26 GMT Subject: Counting nested loop iterations In-Reply-To: <1142541790.500101.260760@v46g2000cwv.googlegroups.com> References: <1142539976.631204.108260@u72g2000cwu.googlegroups.com> <1142541790.500101.260760@v46g2000cwv.googlegroups.com> Message-ID: Derek Basch wrote: >> Depending on the types of the containers in question, you could use: >> >> len(zoo) * len(animal) > > I think this would give me the total iterations but I wouldn't be able > to get a running count. Correct? Correct. If you need a running count, maintain a counter (or enumerate()). From gongcheng_g at hotmail.com Fri Mar 31 04:53:53 2006 From: gongcheng_g at hotmail.com (ChengGong) Date: 31 Mar 2006 01:53:53 -0800 Subject: Copy files Message-ID: <1143798833.637914.219000@t31g2000cwb.googlegroups.com> How can I copy a file from one folder to another(subfolder) without change and property. I work on zope. From uymqlp502 at sneakemail.com Thu Mar 9 19:56:46 2006 From: uymqlp502 at sneakemail.com (Russ) Date: 9 Mar 2006 16:56:46 -0800 Subject: output formatting for classes Message-ID: <1141952206.246076.286400@v46g2000cwv.googlegroups.com> I'd like to get output formatting for my own classes that mimics the built-in output formatting. For example, >>> x = 4.54 >>> print "%4.2f" % x 4.54 In other words, if I substitute a class instance for "x" above, I'd like to make the format string apply to an element or elements of the instance. Can I somehow overload the "%" operator for that? Thanks. On an unrelated matter, I think the complex class in Python is too complex, so I plan to clean it up and implement it right. (just kidding, folks!) From dabbaking at gmail.com Sun Mar 19 09:25:21 2006 From: dabbaking at gmail.com (Dave) Date: 19 Mar 2006 06:25:21 -0800 Subject: Getting .NET SDK to work with Python 2.4.2 In-Reply-To: References: <1142721716.734835.157980@z34g2000cwc.googlegroups.com> <441D5181.2060103@v.loewis.de> <1142773131.890196.309940@i39g2000cwa.googlegroups.com> Message-ID: <1142778321.691159.120860@j33g2000cwa.googlegroups.com> So this means that I have to download .NET 1.1 SDK. Visual Studio 8 comes with msvcrt.lib, but im assuming it's the wrong version. From bencvt at gmail.com Sat Mar 18 02:02:13 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 17 Mar 2006 23:02:13 -0800 Subject: Importing an output from another function In-Reply-To: References: <1142626528.204581.179350@v46g2000cwv.googlegroups.com> <1142627019.614450.250540@i40g2000cwc.googlegroups.com> <1142628076.041352.320560@i40g2000cwc.googlegroups.com> <1142629118.886810.251200@u72g2000cwu.googlegroups.com> Message-ID: <1142665333.013928.104070@i40g2000cwc.googlegroups.com> James Stroud wrote: > Try this (I think its called "argument expansion", but I really don't > know what its called, so I can't point you to docs): > > def Func1(): > choice = ('A', 'B', 'C') > output = random.choice(choice) > output2 = random.choice(choice) > return output, output2 > > def Func2(*items): > print items > > output = Func1() > Func2(*output1) Single asterisk == "arbitrary argument list". Useful in certain patterns, but not something you use every day. Documentation is in the tutorial: http://www.python.org/doc/current/tut/node6.html#SECTION006730000000000000000 PS: Like "self" for class instance methods, "*args" is the conventional name of the arbitrary argument list. --Ben From rganesan at myrealbox.com Wed Mar 1 06:44:05 2006 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Wed, 01 Mar 2006 17:14:05 +0530 Subject: pysqlite problem References: <1141212172.445009.230610@i39g2000cwa.googlegroups.com> Message-ID: >>>>> bapolis writes: > con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES) ^^^^^^^^^^ Did you really intend this? Since you're opening a database in memory, you will have access to tbl1 only if you create the table after the connect. Ganesan -- Ganesan Rajagopal (rganesan at debian.org) | GPG Key: 1024D/5D8C12EA Web: http://employees.org/~rganesan | http://rganesan.blogspot.com From Ch.Ehrlicher at gmx.de Fri Mar 10 01:50:09 2006 From: Ch.Ehrlicher at gmx.de (Christian Ehrlicher) Date: Fri, 10 Mar 2006 07:50:09 +0100 (MET) Subject: Licensing question Message-ID: <570.1141973409@www101.gmx.net> Hi, I've got a question about your python license. For the (lgpl'd) kdewin32 - layer (some unix functions for kdelibs4/win32) I need a mmap implementation. Can I use your code within kdewin32-lib? I don't think that the resulting code will contain a lot of similarities with your code (apart from the calls to CreateFileMapping/MapViewOfFile) but it would be nice to see what problems you had so we don't need to investigate them once more... Thx, Christian -- Echte DSL-Flatrate dauerhaft f?r 0,- Euro*! "Feel free" mit GMX DSL! http://www.gmx.net/de/go/dsl From foobarbazqux at ftml.net Fri Mar 10 12:43:03 2006 From: foobarbazqux at ftml.net (Bill) Date: 10 Mar 2006 09:43:03 -0800 Subject: accessors and lazy initialization Message-ID: <1142012583.875674.138320@v46g2000cwv.googlegroups.com> Hello -- I'm a Java programmer who's slowly getting up to speed in Python. In general I try to initialize the state of my objects as late as possible, in the accessor. So if I have a member "_foo", my accessor is something like: public FooType getFoo() { if (_foo == null) { // initialize _foo here } return _foo; } I'd like to do lazy initialization in Python as well: def getFoo(): try: return _foo except AttributeError: # initialize _foo here return _foo This seems a little clunky. Is there a more Pythonic way of looking at this? Thanks -- Bill. From jstroud at ucla.edu Sun Mar 5 15:26:32 2006 From: jstroud at ucla.edu (James Stroud) Date: Sun, 05 Mar 2006 12:26:32 -0800 Subject: Separating elements from a list according to preceding element In-Reply-To: <1141589424.031872.309820@j33g2000cwa.googlegroups.com> References: <1141587629.918414.245530@t39g2000cwt.googlegroups.com> <1141589424.031872.309820@j33g2000cwa.googlegroups.com> Message-ID: Gerard Flanagan wrote: > Rob Cowie wrote: > >>I'm having a bit of trouble with this so any help would be gratefully >>recieved... >> >>After splitting up a url I have a string of the form >>'tag1+tag2+tag3-tag4', or '-tag1-tag2' etc. The first tag will only be >>preceeded by an operator if it is a '-', if it is preceded by nothing, >>'+' is to be assumed. >> >>Using re.split, I can generate a list that looks thus: >>['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4'] >> >>I wish to derive two lists - each containing either tags to be >>included, or tags to be excluded. My idea was to take an element, >>examine what element precedes it and accordingly, insert it into the >>relevant list. However, I have not been successful. >> >>Is there a better way that I have not considered? If this method is >>suitable, how might I implement it? >> >>Thanks all, >> >>Rob Cowie > > > a = [ '+', 'tag1', '+', 'tag2', '-', 'tag3', '+', 'tag4' ] > > import itertools > > b = list(itertools.islice(a,0,8,2)) > c = list(itertools.islice(a,1,8,2)) > > result1 = [x[1] for x in itertools.izip(b,c) if x[0] == '+'] > result2 = [x[1] for x in itertools.izip(b,c) if x[0] == '-'] > > print > print result1 > print result2 > > > Gerard > Unfortunately this does not address the complete specification: >>> a = [ 'tag1', '+', 'tag2', '-', 'tag3', '+', 'tag4' ] >>> >>> import itertools >>> >>> b = list(itertools.islice(a,0,len(a),2)) >>> c = list(itertools.islice(a,1,len(a),2)) >>> >>> result1 = [x[1] for x in itertools.izip(b,c) if x[0] == '+'] >>> result2 = [x[1] for x in itertools.izip(b,c) if x[0] == '-'] >>> >>> print >>> print result1 [] >>> print result2 [] Need to check for the absence of that first op. James From kent at kentsjohnson.com Wed Mar 15 09:48:06 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 15 Mar 2006 09:48:06 -0500 Subject: Install Universal Encoding Detector In-Reply-To: <1142430310.530681.321760@i39g2000cwa.googlegroups.com> References: <1142430310.530681.321760@i39g2000cwa.googlegroups.com> Message-ID: <44182436$1_2@newspeer2.tds.net> Jacob wrote: > How do I install Universal Encoding Detector > (http://chardet.feedparser.org/)? The usual process: download unpack with your favorite tool - tar or WinZip, maybe cd chardet-1.0 python setup.py install Kent From kent at kentsjohnson.com Wed Mar 8 06:05:26 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 08 Mar 2006 06:05:26 -0500 Subject: generators shared among threads In-Reply-To: <7xzmk2nhu9.fsf@ruckus.brouhaha.com> References: <1141497912.606351.232440@j33g2000cwa.googlegroups.com> <1hbo9a3.1pfr3uy160d79iN%aleaxit@yahoo.com> <7xzmk2nhu9.fsf@ruckus.brouhaha.com> Message-ID: <440eb5ad_2@newspeer2.tds.net> Paul Rubin wrote: > Hmm (untested, like above): > > class Synchronized: > def __init__(self, generator): > self.gen = generator > self.lock = threading.Lock() > def next(self): > self.lock.acquire() > try: > yield self.gen.next() > finally: > self.lock.release() > > synchronized_counter = Synchronized(itertools.count()) > > That isn't a general solution but can be convenient (if I didn't mess > it up). Maybe there's a more general recipe somewhere. This code is not allowed in Python 2.4. From PEP 255: Restriction: A yield statement is not allowed in the try clause of a try/finally construct. The difficulty is that there's no guarantee the generator will ever be resumed, hence no guarantee that the finally block will ever get executed; that's too much a violation of finally's purpose to bear. Even if this was allowed, ISTM the semantics might be the same as your previous attempt - I would expect the finally to be executed after the yield returns, meaning the lock would be held during the yield. Python 2.5 will allow this (see PEP 342) but from the examples it seems the finally won't execute until the yield returns. Kent From diffuser78 at gmail.com Wed Mar 8 16:23:44 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 8 Mar 2006 13:23:44 -0800 Subject: python debugging question Message-ID: <1141853024.196597.49410@j52g2000cwj.googlegroups.com> I am a python newbie. I have writen some 500 lines of code. There are 4 classes and in all 5 files. Now, I am trying to run the program. I am getting wrong values for the simulation results. Is there any debugging facilities in python which would let me go step by step and check the values of the variables at every step. I have done something like this in MS Visual Stdio 6.0 sometime back. For python, I am using SPE. what is a good way of debugging such large and iterative programs ? Any tips. Every help is appreciated. Thanks From oliphant.travis at ieee.org Tue Mar 14 04:05:43 2006 From: oliphant.travis at ieee.org (Travis Oliphant) Date: Tue, 14 Mar 2006 02:05:43 -0700 Subject: [ANN] NumPy 0.9.6 released Message-ID: <44168767.80803@ieee.org> This post is to announce the release of NumPy 0.9.6 which fixes some important bugs and has several speed improvments. NumPy is a multi-dimensional array-package for Python that allows rapid high-level array computing with Python. It is successor to both Numeric and Numarray. More information at http://numeric.scipy.org The release notes are attached: Best regards, NumPy Developers -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: release-notes-0.9.6 URL: From bdesth.quelquechose at free.quelquepart.fr Wed Mar 1 20:35:47 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 02 Mar 2006 02:35:47 +0100 Subject: [coding style] Searching for uniqness in a list of data In-Reply-To: References: <1141228140.331259.8060@j33g2000cwa.googlegroups.com> Message-ID: <440622a4$0$11260$626a54ce@news.free.fr> Claudio Grondi a ?crit : (snip) > > list=['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8v_pol_ms','1p3m_3.3-18.v_sal_ms'] Avoid using 'list' as an identifier. (snip) From sjmachin at lexicon.net Fri Mar 24 06:40:44 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 24 Mar 2006 22:40:44 +1100 Subject: encoding problems =?ISO-8859-1?Q?=28=E9_and_=E8=29?= In-Reply-To: References: <44230fa6$1@news.eftel.com> Message-ID: <4423dacb$1@news.eftel.com> On 24/03/2006 8:11 PM, Duncan Booth wrote: > Peter Otten wrote: > > >>>You can replace ALL of this upshifting and accent removal in one blow >>>by using the string translate() method with a suitable table. >> >>Only if you convert to unicode first or if your data maintains 1 byte >>== 1 character, in particular it is not UTF-8. >> > > > There's a nice little codec from Skip Montaro for removing accents from For the benefit of those who may read only this far, it is NOT nice. > latin-1 encoded strings. It also has an error handler so you can convert > from unicode to ascii and strip all the accents as you do so: > > http://orca.mojam.com/~skip/python/latscii.py > > >>>>import latscii >>>>import htmlentitydefs >>>>print u'\u00c9'.encode('ascii','replacelatscii') > > E > > > So Bussiere could replace a large chunk of his code with: Could, but definitely shouldn't. > > ligneA = ligneA.decode(INPUTENCODING).encode('ascii', 'replacelatscii') > ligneA = ligneA.upper() > > INPUTENCODING is 'utf8' unless (one possible explanation for his problem) > his files are actually in some different encoding. > > Unfortunately, just as I finished writing this I discovered that the > latscii module isn't as robust as I thought, it blows up on consecutive > accented characters. > > :( > Some of the transformations are a little unfortunate :-( 0x00d0: ord('D'), # ? 0x00f0: ord('o'), # ? Icelandic capital eth becomes D, OK; but the small letter becomes o!!! The Icelandic thorn letters become P & p (based on physical appearance), when they should become Th and th. The German letter Eszett (00DF) becomes B (appearance) when it should be ss. Creating alphabetics out of punctuation is scarcely something that bussiere should be interested in: 0x00a2: ord('c'), # ? 0x00a4: ord('o'), # ? 0x00a5: ord('Y'), # ? 0x00a7: ord('S'), # ? 0x00a9: ord('c'), # ? 0x00ae: ord('R'), # ? 0x00b6: ord('P'), # ? From fredrik at pythonware.com Sat Mar 11 04:13:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 11 Mar 2006 10:13:20 +0100 Subject: counting number of (overlapping) occurances References: <1141968108.977332.261010@i40g2000cwc.googlegroups.com><7x3bhq7tf0.fsf@ruckus.brouhaha.com><1141970477.071343.160300@j52g2000cwj.googlegroups.com> Message-ID: Steven D'Aprano wrote > You should always quote enough of the previous poster's message to give > context. Messages sometimes go missing in Usenet, and people won't have > the foggiest idea what you are talking about. one would think that given how many Pythoneers we now have working for google, at least one of them could go fix the horridly broken posting interface in googlegroups... ::: for those who use googlegroups and prefer to make a least a little sense to people read this newsgroup/mailing list using other tools, please click "show options" and use the "reply" link at the top of the message instead of the link with the same name at the bottom. From max at alcyone.com Mon Mar 27 17:25:23 2006 From: max at alcyone.com (Erik Max Francis) Date: Mon, 27 Mar 2006 14:25:23 -0800 Subject: Difference between 'is' and '==' In-Reply-To: References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com><4427d287$0$38669$edfadb0f@dread12.news.tele.dk> Message-ID: Terry Reedy wrote: > The Python specification allows but does not require such behind-the-scenes > implementation optimization hacks. As released, CPython 2.4 caches -5 to > 99, I believe. In 2.5, the upper limit was increased to 256. The limits > are in a pair of #define statements in the int object source file. Anyone > who compiles from source can adjust as desired (though the corresponding > test will fail unless also adjusted ;-). > > I think the visibility of this implementation detail from Python code is an > example of a leaky abstraction. For more, see > http://www.joelonsoftware.com/articles/LeakyAbstractions.html I don't see that as quite the same thing. That you can fiddle around with the `is` operator to investigate how small integers are cached doesn't really reveal any profound underlying abstraction, except that maybe all Python entities are true objects and that integers are immutable, which are things hopefully everyone was already aware of. If you're trying to test integer equality, you should be using the `==` operator, not the `is` operator, so what you find out about how things are caching is really irrelevant. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis And covenants, without the sword, are but words and of no strength to secure a man at all. -- Thomas Hobbes, 1588-1679 From fake at nospam.no Mon Mar 6 19:25:41 2006 From: fake at nospam.no (Blackbird) Date: Tue, 7 Mar 2006 01:25:41 +0100 Subject: %r References: <75-dnc5y7fLN-ZHZRVnzvA@telenor.com> <76WdnakbMbHG45HZ4p2dnA@telenor.com> Message-ID: Peter Hansen wrote: > [...]> > On the other hand, if 'something' is actually some arbitrary object, > then it's definitely not always true, especially for anything not > built in to Python. > > -Peter Yes, I had strings in mind. And I guess it will work with the other primitive types, but anything that repr to something like '' will crash, since it's not a valid Python expression. Is the interpreter in fact using repr(), or parts of it, to generate output when you type an expression at the command prompt? The results sure look similar. Blackbird From bearophileHUGS at lycos.com Fri Mar 24 14:32:57 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 24 Mar 2006 11:32:57 -0800 Subject: Help: Creating condensed expressions In-Reply-To: <44244798$0$18927$626a54ce@news.free.fr> References: <44244798$0$18927$626a54ce@news.free.fr> Message-ID: <1143228777.703813.62260@z34g2000cwc.googlegroups.com> Nevermind, I didn't understand the problem/question... Sorry. Bye, bearophile From Aiwass333 at gmail.com Fri Mar 31 11:27:04 2006 From: Aiwass333 at gmail.com (RunLevelZero) Date: 31 Mar 2006 08:27:04 -0800 Subject: re.sub problem In-Reply-To: <1143812012.143560.24370@i40g2000cwc.googlegroups.com> References: <1143812012.143560.24370@i40g2000cwc.googlegroups.com> Message-ID: <1143822424.549401.250090@z34g2000cwc.googlegroups.com> Okay I just woke up and haven't had enough coffee so if I'm off here please forgive me. Are you saying that if there is an emptly line then it borks? If so just use re.S ( re.DOTALL ) and that should take care of it. It will treat the ( . ) special. Otherwise it ignores new lines. From johnjsal at NOSPAMgmail.com Sat Mar 25 01:34:06 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 25 Mar 2006 01:34:06 -0500 Subject: a problem to solve In-Reply-To: References: <5oiUf.1818$No6.41433@news.tufts.edu> <1143237220.103038.52200@t31g2000cwb.googlegroups.com> <1143251777.489064.28690@u72g2000cwu.googlegroups.com> Message-ID: <66idnRFWy481ebnZnZ2dnUVZ_vydnZ2d@rcn.net> John Salerno wrote: > mensanator at aol.com wrote: > >> No. First of all, combining them with the & operator would be >> the asnswer to having all four lamps lit in the same position. >> But you want exactly 3 (in any combination). The correct way >> to combine the switches (using my answer of a[7] b[2] c[5] d[3]) >> is to use the boolean expression I gave you initially: > > Ah, that makes sense. I think I have a handle on it now. Of course, you > did the grunt work of making the hex list, which might not have been so > fun, but now I can work on using it to get the solution. Once I do, I'd > love to compare my answer to yours, because something tells me yours > will be much more elegant. :) p.s. is there an xor operator in python? From DPETTITT at albemarle.org Sat Mar 4 08:20:15 2006 From: DPETTITT at albemarle.org (Damon Pettitt) Date: Sat, 4 Mar 2006 08:20:15 -0500 Subject: Help with os.spawnv Message-ID: <8993047763A5014EB383CE3CAFDB5B980329F0EA@COBEXCH2K301.cob.albco> I'm not sure if this is how I'm supposed to post, but I saw a thread entitled, "Help with os.spawnv", that I wanted to respond to. I believe if you change the variable pyScript from: "E:\\Documents and Settings\\Administrator\\Desktop\\Ian\\GIS\\Python\\subProcess2.py" to '"E:\Documents and Settings\Administrator\Desktop\Ian\GIS\Python\subProcess2.py"' (this basically uses a single backslash and a single quote preceding the first double quote and a single quote just after the last double quote). your script would work. Damon Pettitt From rdavis at bastools.com Mon Mar 27 08:15:36 2006 From: rdavis at bastools.com (Ronald Davis) Date: Mon, 27 Mar 2006 08:15:36 -0500 Subject: Advice for Python and Web Server/Services? In-Reply-To: <2v0e22p139gi75d49q36ifmbbfi4u0sn7v@4ax.com> References: <2v0e22p139gi75d49q36ifmbbfi4u0sn7v@4ax.com> Message-ID: <200603270815.36694.rdavis@bastools.com> On Sunday 26 March 2006 5:00 pm, Dennis Lee Bieber wrote: > Any possibility you need to specify an option on the socket > connections to reuse-sockets without the normal time-out? The problem turned out to be keep-alive. Apparently, Comcast is limiting my inbound connections. Apache keeps the connections alive so it works fine. The Python servers don't support keep-alive and are using up the available connections too quickly. I'm now using Apache as a proxy to the Python server and it works well. Thanks for the response. > On Sun, 26 Mar 2006 14:55:12 -0500, Ron Davis > > declaimed the following in comp.lang.python: > > I've looked in to fastcgi and mod_python but I'm not sure either is what > > I need. What I want is for my Python program to be polling the web > > services 24/7 and Apache to serve static pages by itself but call a > > function in my already running Python program for files with a certain > > extension (.xml for example). > > I think you'll first need to disconnect the two sides... The program > doing the polling has to run completely stand-alone from your own > web-server. I also think you'll need to create some independent > (file-system?) store which the polling program can write to; so your web > server page can do the selected retrieval -- but since you don't want a > database capable of concurrent access... The polling program needs to > include an asynchronous or threaded scheme with a local socket so the > web server (CGI) process can connect to it and requests the poller to > return the data. > > > Ideally, I'd like to figure out why the Python servers are having > > problems. This is a very low volume system so straight Python would be > > great if I can get it working. > > Any possibility you need to specify an option on the socket > connections to reuse-sockets without the normal time-out? > -- > > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < -- Ron Davis Custom Software Engineering From usenet at mulch.ca Fri Mar 31 22:57:11 2006 From: usenet at mulch.ca (usenet at mulch.ca) Date: 31 Mar 2006 19:57:11 -0800 Subject: Logging and threading Message-ID: <1143863831.438403.91610@i40g2000cwc.googlegroups.com> I'm having some problems getting the logging module to work with the threading module. I've narrowed the problem down to the following code: import logging, threading update_log = logging.getLogger('update_log') update_log.addHandler(logging.FileHandler("/tmp/update_log")) class dlThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): ul = logging.getLogger('update_log') ul.warn("log this") print "finished" t = dlThread() t.start() When executed, I receive the following exception: Traceback (most recent call last): File "/usr/local/lib/python2.4/logging/__init__.py", line 735, in emit self.stream.write(fs % msg) ValueError: I/O operation on closed file The exception isn't fatal though, as the print "finished" line is executed. Alternately, if I run dlThread.run directly everything works as I would expect, albeit without the multithreading. Since the logging module is advertised as being threadsafe, I suspect there's something basic I don't understand about threads. -Alex From scott.daniels at acm.org Fri Mar 3 13:06:45 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 03 Mar 2006 10:06:45 -0800 Subject: How much does Python optimize? In-Reply-To: References: Message-ID: <440883db$1@nntp0.pdx.net> Blackbird wrote: > I think > > for i in range(10): > > > is more readable than a while loop with explicit incrementation of i. > However, range(10) in the command interpreter obviously returns a list. Is > this list optimized away in the code above, or is it actually constructed > internally? (With, say, CPython in one of the recent versions.) Yup, and if you are tuning a piece of code to the wall, you should time it and possibly care. Likely you are not, and the timing makes no difference. Someday, range will behave like xrange automagically, and in the meantime your code will read just fine. If you are in trouble now, your code reads much more like: for i in range(100000): ... The general rule is make the code clear, measure if its too slow, and "don't worry, be happy (yagni)." --Scott David Daniels scott.daniels at acm.org From ask at me Mon Mar 27 20:54:25 2006 From: ask at me (AndyL) Date: Mon, 27 Mar 2006 20:54:25 -0500 Subject: what is the the best way to express following: In-Reply-To: References: <_uOdnaBMCLmcPLXZRVn-uA@comcast.com> Message-ID: James Stroud wrote: > Here is a suggestion > > todo = {(int, long):abc, (str,):afg, (tuple, list):ijk} > todo[type(key)]() Is not that a shortcut? I have got "KeyError" exception ... From gau.tai at gmail.com Fri Mar 10 13:25:35 2006 From: gau.tai at gmail.com (gau.tai at gmail.com) Date: 10 Mar 2006 10:25:35 -0800 Subject: MS Access db (mdb): viewing table attributes In-Reply-To: References: <1142013201.717227.282050@i39g2000cwa.googlegroups.com> Message-ID: <1142015135.286529.209020@e56g2000cwe.googlegroups.com> Here is the full code I'm using now to try out your sample: import dbi, odbc import win32com.client from pprint import pprint #sample code to list all tables in the selected database daoEngine = win32com.client.Dispatch('DAO.DBEngine.36') dtbs = daoEngine.OpenDatabase('database.mdb') for table in dtbs.TableDefs: if table.Name[:4] <> "MSys" and table.Name[:4] <> "~TMP": pprint(table.Name.encode('utf-8')) #sample code that will execute a stored query with parameters dbconn = odbc.odbc('DSN=db; UID=user; PWD=pass') dbcursor = dbconn.cursor() dbcursor.execute('execute "result specs" 1') dbcursor.execute('SELECT column1, column2, COUNT(*) FROM Weight ' + 'WHERE column1 < column2 ' + 'GROUP BY column1, column2') #pprint(dbcursor.fetchall()) dbcursor.close() dbconn.close() I get the error: dbcursor.execute('SELECT column1, column2, COUNT(*) FROM Weight ' + dbi.program-error: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 2. in EXEC From fuzzyman at gmail.com Fri Mar 10 19:01:08 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 10 Mar 2006 16:01:08 -0800 Subject: why use special config formats? In-Reply-To: <1142004363.863051.29090@j33g2000cwa.googlegroups.com> References: <1142002082.976945.261900@e56g2000cwe.googlegroups.com> <1142004363.863051.29090@j33g2000cwa.googlegroups.com> Message-ID: <1142035268.182095.14900@j52g2000cwj.googlegroups.com> tomerfiliba at gmail.com wrote: > if you are really so scared of letting others exploit your config > scripts, then use the second, pickled fashion. that way you can store > the file at $HOME/blah-config.pkl, and everybody's happy. > > still, my point is we dont need special config mechanisms, since the > builtin ones, like object persistency (sp) or python scripts are good > enough, less buggy, and dont require you to learn thousands of config > formats. > Well... ConfigObj uses the same format as ConfigParser, which the basic ini style. The message is that config files are for users, and so should be in a format convenient for them - not for the machine. Call your users cry-babies if yu want, you won't have many... > and you can even edit pickled files by hand (protocol 0 i believe). > it's not that complicated. > If you're happy with a hardwired config file, you don't need a config file at all. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > > -tomer From johnjsal at NOSPAMgmail.com Mon Mar 27 14:17:15 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 27 Mar 2006 19:17:15 GMT Subject: problems with looping, i suppose In-Reply-To: References: <1143486277.480720.148040@t31g2000cwb.googlegroups.com> Message-ID: <%SWVf.1839$No6.41612@news.tufts.edu> John Salerno wrote: > I think it has to do with the exception I'm using. For the leap year > program, it should be ValueError. For the other one, its' a combination > of that and the input function. Hmm, turns out something was wrong with the indentation of the second while loop! Even though it looked correct, it created problems when I opened it in IDLE, so I just unindented the whole thing and reindented it manually, and now it works. From claird at lairds.us Mon Mar 20 19:08:02 2006 From: claird at lairds.us (Cameron Laird) Date: Tue, 21 Mar 2006 00:08:02 GMT Subject: Remote teamwork anecdotes (was: Where can we find top-notch python developers?) References: <1hceomq.1whcmq2114jly6N%aleaxit@yahoo.com> Message-ID: <2op3f3-uf6.ln1@lairds.us> In article <1hceomq.1whcmq2114jly6N%aleaxit at yahoo.com>, Alex Martelli wrote: . . . >Unfortunately, I entirely understand _why_ most software development >firms prefer face-to-face employees: when I found myself, back when I >was a freelance consultant, alternatively working remotely for some >time, and at the client's office for another part of the time, I saw my >productivity soar by 3-4 times when I was working locally, physically >right next to the rest of the team, rather than remotely -- nowadays, >open-source projects have discovered the same issue, which is why they >have "sprints" with everybody gathering in the same place, where SO much >more good work gets done than when everybody's connected to each other >only via the net... Alistair Cockburn makes similar observations in his >book "Agile Software Development", how it seems projects can be truly >agile only if the team is co-located... ah well:-(. It would be SO much >more convenient, for workers and firms both, if reality would be so kind >to us as to be different!-) . . . Now I'm uneasy. Alex, you're describing something that's different from my experience, and I'm alert enough to suspect my own judgment when it differs so sharply from yours. Briefly, remote collaboration works for me. I work on customer premises part of the year, and, while there are multipliers, my estimate is that they're far closer to one than four. Sometimes they're less than one--I get rather impatient with a lot of small talk, and locating the approved meeting room, and waiting for approved equipment, and ... I like working with others, and sometimes indeed it's a huge gain. Sometimes it's just noise. From codecraig at gmail.com Thu Mar 30 09:28:46 2006 From: codecraig at gmail.com (abcd) Date: 30 Mar 2006 06:28:46 -0800 Subject: How to determine an object is "scriptable" In-Reply-To: <4927udFmla3dU1@news.dfncis.de> References: <1143726903.153135.317880@j33g2000cwa.googlegroups.com> <4927udFmla3dU1@news.dfncis.de> Message-ID: <1143728926.215531.276550@e56g2000cwe.googlegroups.com> Daniel Evers wrote: > Right. You can check this e.g. with > > hasattr(x, "__getitem__") > > because the __getitem__ method is used for indexing. Thanks...that is what I was looking for! From johnjsal at NOSPAMgmail.com Mon Mar 20 15:16:25 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 20 Mar 2006 20:16:25 GMT Subject: why isn't Unicode the default encoding? In-Reply-To: References: Message-ID: Robert Kern wrote: > Well, *I* use UTF-8, but that's neither here nor there. I see UTF-8 a lot, but this particular book also mentions that UTF-16 is the most common. Is that true? >> Why can't Unicode replace them so we no longer need the 'u' >> prefix or the encoding tricks? > > It would break a hell of a lot of code. Try using the -U command line argument > to the Python interpreter. That makes unicode strings default. I figured this might have something to do with it, but then again I thought that Unicode was created as a subset of ASCII and Latin-1 so that they would be compatible...but I guess it's never that easy. :) From danbrwn at gmail.com Fri Mar 24 06:45:04 2006 From: danbrwn at gmail.com (Dan) Date: 24 Mar 2006 03:45:04 -0800 Subject: New development windows, IronPython or PythonWin References: <1143135013.513865.103820@u72g2000cwu.googlegroups.com> <1143166004.664604.207250@j33g2000cwa.googlegroups.com> <87slp8pfnv.fsf@ieee.org> Message-ID: <1143200704.159705.60350@j33g2000cwa.googlegroups.com> >> IronPython is currently nowhere near production quality. I would not >> recommend it. I realise its in beta. But long term, do you think that the win32com, win32gui etc... will have no support because everyone jumps on the Microsoft bandwagon? Aren't the windows support extensions supported primarily by one guy, Mark Hammond? As a developer, this seams to leave me with a vulnerability long term. Thanks for the advise. From cookedm+news at physics.mcmaster.ca Fri Mar 17 17:20:02 2006 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 17 Mar 2006 17:20:02 -0500 Subject: "pow" (power) function References: <1142465999.800332.73050@i39g2000cwa.googlegroups.com> <1142470299.753531.269360@j52g2000cwj.googlegroups.com> <1142474325.396362.78920@u72g2000cwu.googlegroups.com> Message-ID: "Russ" writes: > Ben Cartwright wrote: >> Russ wrote: > >> > Does "pow(x,2)" simply square x, or does it first compute logarithms >> > (as would be necessary if the exponent were not an integer)? >> >> >> The former, using binary exponentiation (quite fast), assuming x is an >> int or long. >> >> If x is a float, Python coerces the 2 to 2.0, and CPython's float_pow() >> function is called. This function calls libm's pow(), which in turn >> uses logarithms. > > I just did a little time test (which I should have done *before* my > original post!), and 2.0**2 seems to be about twice as fast as > pow(2.0,2). That seems consistent with your claim above. > > I'm a bit surprised that pow() would use logarithms even if the > exponent is an integer. I suppose that just checking for an integer > exponent could blow away the gain that would be achieved by avoiding > logarithms. On the other hand, I would think that using logarithms > could introduce a tiny error (e.g., pow(2.0,2) = 3.9999999996 <- made > up result) that wouldn't occur with multiplication. It depends on the libm implementation of pow() whether logarithms are used for integer exponents. I'm looking at glibc's (the libc used on Linux) implementation for Intel processors, and it does optimize integers. That routine is written in assembly language, btw. >> > Does "x**0.5" use the same algorithm as "sqrt(x)", or does it use some >> > other (perhaps less efficient) algorithm based on logarithms? >> >> The latter, and that algorithm is libm's pow(). Except for a few >> special cases that Python handles, all floating point exponentation is >> left to libm. Checking to see if the exponent is 0.5 is not one of >> those special cases. > > I just did another little time test comparing 2.0**0.5 with sqrt(2.0). > Surprisingly, 2.0**0.5 seems to take around a third less time. > > None of these differences are really significant unless one is doing > super-heavy-duty number crunching, of course, but I was just curious. > Thanks for the information. And if you are, you'd likely be doing it on more than one number, in which case you'd probably want to use numpy. We've optimized x**n so that it does handle n=0.5 and integers specially; it makes more sense to do this for an array of numbers where you can do the special manipulation of the exponent, and then apply that to all the numbers in the array at once. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From mwilson-to at sympatico.ca Tue Mar 7 11:24:21 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Tue, 07 Mar 2006 11:24:21 -0500 Subject: inserting into a list In-Reply-To: References: Message-ID: John Salerno wrote: > Christoph Haas wrote: >> L[2:2]=[3] [ ... ] What if you wanted to insert an actual list into that slot? Would > you have to wrap it in double brackets? Yep. It's a strong-typing thing. Slices of lists are lists, and therefore what you assign to one has got to be a list, or convertible to a list (a tuple would work.) 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,3,4] >>> a[2:3] [4] >>> a[2:2] [] >>> a[1:1]=[2] >>> a [1, 2, 3, 4] >>> a[1:2] [2] Mel. From fabioxgn at gmail.com Mon Mar 13 02:24:22 2006 From: fabioxgn at gmail.com (sapo) Date: 12 Mar 2006 23:24:22 -0800 Subject: Toggle button in a ListStore in pygtk, i cant make it work! Message-ID: <1142234662.028568.293570@z34g2000cwc.googlegroups.com> This is my code: def list(self): tree = self.principal.get_widget("list") self.list = gtk.ListStore(bool,str) self.options = [1,"programa1"] renderer1 = gtk.CellRendererToggle() renderer1.set_property('activatable', True) renderer1.connect( 'toggled', self.selection, self.list) tree.insert_column_with_attributes(0, "Select",renderer1) renderer2 = gtk.CellRendererText() tree.insert_column_with_attributes(1,"Install",renderer2, text=1) self.list.append(self.options) tree.set_model(self.list) def selection( self, cell, path, model ): model[path][0] = not model[path][0] return It shows up but the toggle button isnt working! what is wrong with this? I m following this example: http://pygtk.org/pygtk2tutorial/sec-CellRenderers.html#sec-EditableActivatableProgram Thanx for any help! From mandelin at cs.berkeley.edu Mon Mar 27 14:48:37 2006 From: mandelin at cs.berkeley.edu (Dave Mandelin) Date: 27 Mar 2006 11:48:37 -0800 Subject: Python C wrapper question References: Message-ID: <1143488917.138237.302450@u72g2000cwu.googlegroups.com> Shi, Jue wrote: > Hello, Gurus, > > I have a question on wrapping C function in Python. > > > My C code is like this: > > typedef void (WINAPI *myCallBack) (unsigned int myarg1, unsigned int myarg2) > > bool myfunc(myCallBack callfunc) > > > Now I want to call myfunc in Python, what should I do? I replied to someone else with the same question. It depends on how you are calling the function. If you are using DynWin/calldll, there is a callback generator gencb.py. -- Want to play tabletop RPGs over the internet? Check out Koboldsoft RPZen: http://www.koboldsoft.com From danmcleran at yahoo.com Wed Mar 1 11:50:24 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 1 Mar 2006 08:50:24 -0800 Subject: Accessing 'mangled' class attrbutes In-Reply-To: <1141226955.820389.87860@z34g2000cwc.googlegroups.com> References: <1141226955.820389.87860@z34g2000cwc.googlegroups.com> Message-ID: <1141231824.077785.97490@e56g2000cwe.googlegroups.com> >>Is there any simple way round this situation in general? It might be safer to use composition instead of inheritance in this case. Assuming that XMLWriter has a write method to write what you want, you could hold a reference to an XMLWriter within your class and pass along write command like: writer = XMLWriter() writer.write(stuff) From aurora00 at gmail.com Thu Mar 9 21:07:17 2006 From: aurora00 at gmail.com (aurora00 at gmail.com) Date: 9 Mar 2006 18:07:17 -0800 Subject: ANN: pyregex 0.5 - command line tools for Python's regular expression Message-ID: <1141956437.647376.98510@z34g2000cwc.googlegroups.com> pyregex is a command line tools for constructing and testing Python's regular expression. Features includes text highlighting, detail break down of match groups, substitution and a syntax quick reference. It is released in the public domain. Screenshot and download from http://tungwaiyip.info/software/pyregex.html. Wai Yip Tung ------------------------------------------------------------------------ Usage: pyregex.py [options] "-"|filename regex [replacement [count]] Test Python regular expressions. Specify test data's filename or use "-" to enter test text from console. Optionally specify a replacement text. Options: -f filter mode -n nnn limit to examine the first nnn lines. default no limit. -m show only matched line. default False Regular Expression Syntax Special Characters ------------------------------------------------------------------------ . matches any character except a newline ^ matches the start of the string $ matches the end of the string or just before the newline at the end of the string * matches 0 or more repetitions of the preceding RE + matches 1 or more repetitions of the preceding RE ? matches 0 or 1 repetitions of the preceding RE {m} exactly m copies of the previous RE should be matched {m,n} matches from m to n repetitions of the preceding RE \ either escapes special characters or signals a special sequence [] indicate a set of characters. Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a "-". Special characters are not active inside sets Including a "^" as the first character match the complement of the set | A|B matches either A or B (...) indicates the start and end of a group (?...) this is an extension notation. See documentation for detail (?iLmsux) I ignorecase; L locale; M multiline; S dotall; U unicode; X verbose *, +, ? and {m,n} are greedy. Append the ? qualifier to match non-greedily. Special Sequences ------------------------------------------------------------------------ \number matches the contents of the group of the same number. Groups are numbered starting from 1 \A matches only at the start of the string \b matches the empty string at the beginning or end of a word \B matches the empty string not at the beginning or end of a word \d matches any decimal digit \D matches any non-digit character \guse the substring matched by the group named 'name' for sub() \s matches any whitespace character \S matches any non-whitespace character \w matches any alphanumeric character and the underscore \W matches any non-alphanumeric character \Z matches only at the end of the string See the Python documentation on Regular Expression Syntax for more detail http://docs.python.org/lib/re-syntax.html From john_sips_teaz at yahooz.com Wed Mar 1 01:58:01 2006 From: john_sips_teaz at yahooz.com (John M. Gabriele) Date: Wed, 01 Mar 2006 01:58:01 -0500 Subject: Python Indentation Problems In-Reply-To: <1141026326.424249.187030@p10g2000cwp.googlegroups.com> References: <1141021286.047172.278030@z34g2000cwc.googlegroups.com> <1141026326.424249.187030@p10g2000cwp.googlegroups.com> Message-ID: Renato wrote: > If you use vi (vim, I hope), then place something like this in your > .vimrc > > set ts=4 > set sw=4 > set expandtab > set ai Or, more verbose: set tabstop=4 set shiftwidth=4 set autoindent > There are a lot more tricks for python in vim (and plugins, and > helpers, and so on), but this is the starting point: tabstops of 4 > places, autoconverted in spaces. Also, when shifting text with < or > > it moves 4 spaces. > Also possibly useful: set shiftround ---John -- (remove zeez if demunging email address) From nessus at mit.edu Thu Mar 9 12:52:50 2006 From: nessus at mit.edu (Douglas Alan) Date: Thu, 09 Mar 2006 12:52:50 -0500 Subject: Python Evangelism References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> Message-ID: rtilley writes: > Steve Holden wrote: >> Doug Bromley wrote: >>> I can see Ruby overtaking Python if we don't ALL do something about it. > I think it's the name. Python. Let's change it to something nicer. I agree that names are very important -- Java would never have caught on the way that it did if Sun had left the name as "Oak". I think you're wrong about the name "Python", though. Snakes are cool and have street cred. That's why there are cars with names like "Cobra" and "Viper". It doesn't matter if the average joe is scared when they see a folder named "python" on their computer, as the average joe isn't a programmer. Ruby didn't start catching on until Ruby on Rails came out. If Python has a naming problem, it's with the name of Django, rather than Python. Firstly, Django doesn't have "Python" in the name, so it doesn't popularize the language behind it, even should Django become very popular. Secondly, Django just doesn't have the ring of "Ruby on Rails". They should change the name to "Blood Python" instead. Okay, well, maybe not. How about "Green Tree Python"? Hmmm, kind of boring. Well, maybe "Python on the Bullet Train"? Okay, too derivative. "Maglev Python"? "Python with Panache"? "Python on Prozac"? I give up. In any case, I'm sure Django was a great musician, but the product needs a better name to have any chance of displacing Rails. |>oug From bobrien18 at yahoo.com Mon Mar 6 15:39:55 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 6 Mar 2006 12:39:55 -0800 Subject: reshape a list? Message-ID: <1141677595.143157.296740@v46g2000cwv.googlegroups.com> I have a list that starts out as a two dimensional list I convert it to a 1D list by: b = sum(a, []) any idea how I can take be and convert it back to a 2D list? From deets at nospam.web.de Wed Mar 8 17:32:59 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 08 Mar 2006 23:32:59 +0100 Subject: reading float from binary data file In-Reply-To: <1141856610.749874.133640@i39g2000cwa.googlegroups.com> References: <1141856610.749874.133640@i39g2000cwa.googlegroups.com> Message-ID: <4794crFeb3kfU1@uni-berlin.de> cesco schrieb: > Hi, > > I have a binary file containing 1000 floating point numbers. I want to > load that file into an array. A way to do it could be the following: > >>>> import array >>>> data = array.array('f') >>>> f = open('FileName.bin', 'rb') >>>> data.fromfile(f, 1000) > > Now I have the following problem: if I don't know how many values the > file contains and I want to read all the values till the last one what > shall I do? Divide the length of the file by the size of one float and use that as argument to fromfile. Diez From g.brandl-nospam at gmx.net Sun Mar 19 18:10:24 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Mon, 20 Mar 2006 00:10:24 +0100 Subject: C-API: A beginner's problem In-Reply-To: References: Message-ID: <4866n0Fi1e6hU1@individual.net> Fabian Steiner wrote: > I recently started learning C since I want to be able to write Python > extension modules. In fact, there is no need for it, but I simply want > to try something new ... > > I tried to implement the bubblesort algorithm in C and to use it in > python; bubblesort.c compiles fine, but whenever I want to import the > modul and call the function I get a segmentation fault. This is what the > code looks like: > > static PyObject *py_bubblesort(PyObject *self, PyObject *args) { > PyObject *seq = NULL, *item, *newseq = NULL; > int seqlen, i; long it; > if(!PyArg_ParseTuple(args, "O", &seq)) { > return NULL; > } > seq = PySequence_Fast(seq, "argument must be iterable"); > if(!seq) { > return NULL; > } > seqlen = PySequence_Fast_GET_SIZE(seq); > int list[seqlen]; > for (i = 0; i <= seqlen; i++) { That is one iteration too much. Use for (i = 0; i < seglen; i++) > item = PySequence_Fast_GET_ITEM(seq, i); Now item is a PyObject*. You'll have to convert it to an integer now: it = PyInt_AsLong(item); if (it == -1 && PyErr_Occurred()) { Py_DECREF(seq); /* set a new exception here if you like */ return NULL; } > list[i] = it; > } > bubblesort(list, seqlen); > newseq = PyList_New(seqlen); > if(!newseq) { Do not forget to DECREF seq: Py_DECREF(seq); > return NULL; > } > for(i = 0; i < seqlen; i++) { > PyList_SetItem(newseq, i, list[i]); List items must be PyObject*s, not plain ints. Use: PyList_SetItem(newseq, i, PyInt_FromLong(list[i])); (This is sloppy error checking, but if PyInt_FromLong fails you're out of memory anyways ;) > } Again, seq is not needed anymore: Py_DECREF(seq); > return newseq; > > bubblesort(int list[], int seqlen) is doing the actual job and it is > working. > > What did I do wrong? As I am quite new to C, I probably made many > mistakes, so please feel free to correct me. There's quite a bit you can overlook, especially stale references to PyObjects. I'm not even sure the code compiles or runs correctly with my corrections ;) Cheers, Georg From hancock at anansispaceworks.com Mon Mar 13 21:37:34 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 13 Mar 2006 20:37:34 -0600 Subject: PEP 8 example of 'Function and method arguments' In-Reply-To: <44159b49$0$11065$e4fe514c@news.xs4all.nl> References: <44159b49$0$11065$e4fe514c@news.xs4all.nl> Message-ID: <20060313203734.5899bd55@samwise.anansi> On Mon, 13 Mar 2006 17:18:16 +0100 "Martin P. Hellwig" wrote: > While I was reading PEP 8 I came across this part: > > """ > Function and method arguments > Always use 'self' for the first argument to instance > methods. Always use 'cls' for the first argument to > class methods. > """ > > Now I'm rather new to programming and unfamiliar to some > basic concepts of OOP. However I wrote most of my classes > in the new style way and by this I have always used > 'self' for the first argument of an Instance method, but > now I'm unsure what actually the difference is between an > instance and a class method is and when to use it in which > case. > > Could somebody please enlighten me (a rtfm/wrong newsgroup > is just as welcome of course), preferably in a short code > example? In short, if you don't know what it is, you don't need it. ;-) So far, the only time I've ever encountered this is with the __new__ method, which, being a classmethod, needs "cls" (which gets loaded with the *class* not the *instance*). -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From johnjsal at NOSPAMgmail.com Thu Mar 2 10:17:11 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 02 Mar 2006 15:17:11 GMT Subject: white space in expressions and argument lists Message-ID: A minor concern, but I'm curious if there is any kind of best practice for using whitespace within expressions and argument lists in the Python world. For example: 1 + 2 or 1+2 func(1,2) or func(1, 2) To me, the space makes it nicer and more readable, but I was surprised to read in Guido's blog that he thinks 1+2 should be the normal way to write it. What does everyone else think? From fredrik at pythonware.com Mon Mar 13 17:20:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Mar 2006 23:20:29 +0100 Subject: Localized month names? References: Message-ID: Jarek Zgoda wrote: > How do I get a list of localized month names for current locale? The > first thing that came to my mind was an ugly hack: > > import datetime > for i in range(12): > # as I remember, all months in 2005 had 1st in days > datetime.date(2005, i + 1, 1).strftime('%B') doesn't look very ugly to me... the strftime tables are hidden deep inside the C library, but I guess you could use the _strptime implementation module to dig out the information you're after: >>> import locale >>> locale.setlocale(locale.LC_ALL, "sv_SE") 'sv_SE' >>> import _strptime >>> vars(_strptime.LocaleTime()) {'lang': ('sv_SE', 'ISO8859-1'), 'am_pm': ['', ''], 'f_month': ['', 'januari', 'februari', 'mars', 'april', 'maj', 'juni', 'juli', 'augusti', 'september', 'oktober', 'november', 'december'], 'LC_date': '%Y-%m-%d', 'a_weekday': ['m\xe5n', 'tis', 'ons', 'tor', 'fre', 'l\xf6r', 's\xf6n'], 'f_weekday': ['m\xe5ndag', 'tisdag', 'onsdag', 'torsdag', 'fredag', 'l\xf6rdag', 's\xf6ndag'], 'LC_date_time': '%a %d %b %Y %H.%M.%S', 'timezone': (frozenset(['utc', 'cet', 'gmt']), frozenset(['cest'])), 'a_month': ['', 'jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'], 'LC_time': '%H.%M.%S'} (I'm pretty sure _strptime uses your ugly hack-approach to extract this information from the C library...) hope this helps! From fabianosidler at gmail.com Sat Mar 11 19:49:22 2006 From: fabianosidler at gmail.com (Fabiano Sidler) Date: Sun, 12 Mar 2006 01:49:22 +0100 Subject: anonymous memory mapping Message-ID: <200603120149.22159.fabianosidler@gmail.com> Hi folks! Is there any way to use anonymous memory mapping in python, versions earlier than 2.5? Greetings, F. Sidler From rrr at ronadam.com Sun Mar 19 16:19:29 2006 From: rrr at ronadam.com (Ron Adam) Date: Sun, 19 Mar 2006 15:19:29 -0600 Subject: Initializing a list of lists In-Reply-To: <1142782140.389645.23500@z34g2000cwc.googlegroups.com> References: <1142782140.389645.23500@z34g2000cwc.googlegroups.com> Message-ID: <4YjTf.130535$4l5.32506@dukeread05> tkpmep at hotmail.com wrote: > I want to create a list of lists, each of which is identical, but which > can be modified independently i.e: > >>>> x = [ [0], [0], [0] ] >>>> x[0].append(1) >>>> x > [[0, 1], [0], [0]] > > The above construct works if I have only few items, but if I have many, > I'd prefer to write >>>> N =3 >>>> x =N*[[0]] >>>> x > [[0], [0], [0]] > > If I now try extending the lists indepently, I cannot, as they all > point to the same list object >>>> x[0].append(1) >>>> x > [[0, 1], [0, 1], [0, 1]] > > Is there a simple way to create a list of independent lists? Try this... x, y, value = 3, 3, 0 L = [[value]*x for i in xrange(y)] Cheers, Ron From workbee at gmail.com Fri Mar 10 23:39:29 2006 From: workbee at gmail.com (Enigma Curry) Date: 10 Mar 2006 20:39:29 -0800 Subject: capturing stdout from lynx.. References: <1142050645.355328.95750@z34g2000cwc.googlegroups.com> Message-ID: <1142051969.349077.157680@u72g2000cwu.googlegroups.com> Does this do what you want? import os filename = "test.html" cmd = os.popen("lynx -dump %s" % filename) output = cmd.read() cmd.close() print output From rpdooling at gmail.com Fri Mar 10 15:44:29 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 Mar 2006 12:44:29 -0800 Subject: MS Access db (mdb): viewing table attributes References: <1142013201.717227.282050@i39g2000cwa.googlegroups.com> <1142015135.286529.209020@e56g2000cwe.googlegroups.com> <1142015868.754519.259200@e56g2000cwe.googlegroups.com> Message-ID: <1142023469.814701.251810@v46g2000cwv.googlegroups.com> >> I was hoping that your code would >> return the column names for me, but it was expecting me to list the >> columns to use. I want to know how to retrieve that list of columns >> through python. I think once you establish connection to the database using Python and mxODBC, then your question becomes an SQL question not a Python question. rpd From Serge.Orlov at gmail.com Wed Mar 22 20:08:07 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 22 Mar 2006 17:08:07 -0800 Subject: python linking In-Reply-To: <1143063512.682459.95050@g10g2000cwb.googlegroups.com> References: <1143063512.682459.95050@g10g2000cwb.googlegroups.com> Message-ID: <1143076087.601977.252530@i40g2000cwc.googlegroups.com> Nancy wrote: > When i link with python2.4.a i get this error. > > ld: Dwarf Error: Invalid or unhandled FORM value: 14. > > I am NOT using the gcc compiler but the linux icc compiler. Google > hits blame it on gcc compiler binutils being out of date. i dont think > thats the problem here. > thanks. And how was python2.4.a was built? with gcc? If you mix compilers you always risk to hit corner cases of integration that compiler writers have not debugged. Serge. From nessus at mit.edu Wed Mar 1 13:15:05 2006 From: nessus at mit.edu (Douglas Alan) Date: Wed, 01 Mar 2006 13:15:05 -0500 Subject: Use empty string for self References: <1141170846.619246.163470@t39g2000cwt.googlegroups.com> Message-ID: Roy Smith writes: > Terry Hancock wrote: >> However, there is a slightly less onerous method which >> is perfectly legit in present Python -- just use "s" >> for "self": > This is being different for the sake of being different. Everybody *knows* > what self means. If you write your code with s instead of self, it just > makes it that much harder for other people to understand it. I always use "s" rather than "self". Are the Python police going to come and arrest me? Have I committed the terrible crime of being unPythonic? (Or should that be un_pythonic?) I rarely find code that follows clear coding conventions to be hard to understand, as long as the coding convention is reasonable and consistent. Something that I do find difficult to understand, as a contrasting example, is C++ code that doesn't prefix instance variables with "_" or "m_" (or what have you), or access them via "this". Without such a cue, I have a hard time figuring out where such variables are coming from. Regarding why I use "s" rather than "self", I don't do this to be different; I do it because I find "self" to be large enough that it is distracting. It's also a word, which demands to be read. (Cognitive psychologists have shown that when words are displayed to you your brain is compelled to read them, even if you don't want to. I experience this personally when I watch TV with my girlfriend who is hearing impaired. The captioning is very annoying to me, because it's hard not to read them, even though I don't want to. The same thing is true of "self".) With too many "self"s everywhere, my brain finds it harder to locate the stuff I'm really interested in. "s." is small enough that I can ignore it, yet big enough to see when I need to know that information. It's not a word, so my brain doesn't feel compelled to read it when I don't want to, and it's shorter, so I can fit more useful code on a line. Breaking up some code onto multiple lines often makes it significantly less readable. (Just ask a typical mathematician, who when shown notations that Computer Science people often use, laugh in puzzlement at their verbosity. Mathematicians probably could not do what they do without having the more succinct notations that they use.) Don't take any of this to mean that succinctness is always better than brevity. It quite often is not. Brevity is good for things that you do over and over and over again. Just ask Python -- it often knows this. It's why there are no "begin" and "end" statements in Python. It's why semicolons aren't required to separate statements that are on different lines. That stuff is extra text that serves little purpose other than to clutter up the typical case. |>oug From aleaxit at yahoo.com Wed Mar 22 00:30:19 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 21 Mar 2006 21:30:19 -0800 Subject: Extending Methods Vs Delegates References: <1142985431.079078.3480@i40g2000cwc.googlegroups.com> Message-ID: <1hckjdk.c55h629l2oz8N%aleaxit@yahoo.com> vbgunz wrote: ... > Python in a nutshell explains on page 80: Delegating to superclass > method (5.1.6.2 in the ebook) that the first example above (extending I'm not using "delegate" in any specialized technical sense, e.g. (picking from a google search on [define:delegate]), "person designated to act for or represent another or others". Here, object, not person, of course. What the Learning book chooses to call ``delegate'' is commonly known in the programming world by the (lousy) name "Template Method design pattern" (I like to call it "self-delegation", but that's just me). I regret Ascher and Lutz's choice to muddy the waters by implying that "delegate" has this very specialized meaning... > above, what is the purpose of calling a sub class method from a super > class instance? What is the application to such a design? The reason I > ask is because it is honest to god confusing and I've heard of > delegates before... Forget the naming: the purpose of the Template Method design pattern is to abstract the structure in the superclass while allowing subclasses to see to the details. A great pattern (w/a lousy name). Several of my presentations (you can find them in the english-language half of www.aleax.it) touch on design patterns in Python. I guess I'll have to write a real essay about that sooner or later -- meanwhile, try to make do with my presentations, my posts , and what you can find by google search on ["template method" design pattern]... Alex From johnjsal at NOSPAMgmail.com Wed Mar 22 15:24:33 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 22 Mar 2006 20:24:33 GMT Subject: a problem to solve Message-ID: <5oiUf.1818$No6.41433@news.tufts.edu> Ok, here's a problem I've sort of assigned to myself for fun, but it's turning out to be quite a pain to wrap my mind around. It's from a puzzle game. It will help if you look at this image: http://www.johnjsal.devisland.net/switches.jpg Here's the situation: Each of the four rows in the diagram is considered a single 'panel'. Each panel has eight 'switches', which are composed of two columns each, and these columns have a total of 20 lights (10 in one column, 10 in the other). The picture hopefully makes this description clear. The shaded boxes denote which lights turn on when you select that particular switch. So, the very first switch in the first row, if turned on, would turn on the first four lights, not the fifth, turn on the sixth, not the seventh, and turn on 8-14, etc. up to the 20th light. You can only turn on one switch per panel, so eventually you will have four switches lit. What you are shooting for is to find a combination of four switches so that exactly three lights in the same location are lit, no more or less. So turning on the first switch in each row would not work, because that would mean that the second light in each switch would be lit, and you can't have all four lit, just three. So anyway, the reason I describe all this isn't so you can solve it for me, because I really want to figure it out. I just was hoping you can give me some tips as to how to implement the algorithm. Maybe Python has some functions that I can use to make it easier than it seems. My plan right now is to do a comparison of panel 1, switch 1, light 1 with panel 2, switch 1, light 1, then panel 3, switch 1, light 1, etc., which sounds scary. I didn't know if Python had a way to compare the whole switch in one step, perhaps. Also, I was wondering how I might implement the switches as data structures. Right now I have them as a list of 32 strings, but I thought maybe some type of bitwise comparisons could help. Anyway, any advice for how to proceed would be great! I hope I described it well enough. From irmen.NOSPAM at xs4all.nl Sun Mar 19 16:11:00 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 19 Mar 2006 22:11:00 +0100 Subject: python library for web discussions In-Reply-To: <1142753598.098579.14080@z34g2000cwc.googlegroups.com> References: <1142753598.098579.14080@z34g2000cwc.googlegroups.com> Message-ID: <441dc8e6$0$11076$e4fe514c@news.xs4all.nl> Amir Michail wrote: > Hi, > > I'm building something like digg/reddit and would like to allow people > to have discussions on various items. > > Is there a simple lightweight python library that I can use (as opposed > to a heavyweight web framework)? Although not necessary, some sort of > scoring/moderation mechanism would be good also (e.g., like > reddit/slashdot). If you don't mind that it is not possible to discuss in "threads", you may want to have a look at my blog server "Frog": http://snakelets.sourceforge.net/frog/ Ah, it doesn't support a scoring/moderation system too. So it may not really suit your needs, but if you can't find something else.... ;-) --Irmen From cito at online.de Tue Mar 21 17:47:08 2006 From: cito at online.de (Christoph Zwerschke) Date: Tue, 21 Mar 2006 23:47:08 +0100 Subject: doctest, unittest, or if __name__='__main__' In-Reply-To: <1142976616.012029.140050@t31g2000cwb.googlegroups.com> References: <1142974528.143287.326360@e56g2000cwe.googlegroups.com> <1142976616.012029.140050@t31g2000cwb.googlegroups.com> Message-ID: john_sips_tea at yahoo.com schrieb: > Anyhow, I'm not attacking doctest, but rather, just trying > to understand why there seems to be two very similar ways > of testing your code built into the system (considering that > one motto around here is "There should be one -- and > preferably only one -- obvious way to do it."). I don't think doctest and unittest are similar ways; they are pretty different ways. Also, the "one obvious way" should not be overstressed and taken as a dogma for libraries, modules and frameworks. Actually, on that level we see the opposite in the Python world: A plethora of tools for XML processing, GUI frameworks, Web frameworks etc. Some think this is deplorable, but I see this as something exciting and positive. -- Christoph From walter at livinglogic.de Fri Mar 24 10:50:18 2006 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Fri, 24 Mar 2006 16:50:18 +0100 Subject: encoding problems (X and X) In-Reply-To: References: <44230fa6$1@news.eftel.com> Message-ID: <4424153A.30306@livinglogic.de> Duncan Booth wrote: > [...] > Unfortunately, just as I finished writing this I discovered that the > latscii module isn't as robust as I thought, it blows up on consecutive > accented characters. > > :( Replace the error handler with this (untested) and it should work with consecutive accented characters: def latscii_error( uerr ): v = [] for c in uerr.object[uerr.start:uerr.end] key = ord(c) try: v.append(unichr(decoding_map[key])) except KeyError: v.append(u"?") return (u"".join(v), uerr.end) codecs.register_error('replacelatscii', latscii_error) Bye, Walter D?rwald From fredrik at pythonware.com Thu Mar 2 11:19:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 2 Mar 2006 17:19:08 +0100 Subject: white space in expressions and argument lists References: Message-ID: John Salerno wrote: > Guido listed a few rules that he'd like to see implemented in 2.5, and > one of them was no more than one consecutive white space. I don't know > how realistic some of those suggestions are, but they seem to be getting > a little to restrictive. in his april 1st, 2005 paper ? http://www.artima.com/weblogs/viewpost.jsp?thread=101968 From adam.deprince at gmail.com Tue Mar 28 11:00:57 2006 From: adam.deprince at gmail.com (Adam DePrince) Date: Tue, 28 Mar 2006 11:00:57 -0500 Subject: in-place string reversal In-Reply-To: <1143555308.009412.295250@z34g2000cwc.googlegroups.com> References: <1143554931.104392.187480@i39g2000cwa.googlegroups.com> <1143555308.009412.295250@z34g2000cwc.googlegroups.com> Message-ID: <1143561658.3305.53.camel@localhost.localdomain> On Tue, 2006-03-28 at 06:15 -0800, Sathyaish wrote: > And that the "extra-memory" operation I've given above is expensive, I > believe. Is there an efficient way to do it? > How big is your string? For short strings (i.e. where large means you don't have enough RAM to hold one extra copy.) >>> "Abc"[::-1] 'cbA' >>> Also, anytime you reach for a for-loop to build a string step by step, you are making a mistake. Consider your example. strText = "foo" strTemp = "" for chr in strText: strTemp = chr + strTemp Each loop you are copying the string again, the timing behavior of your function is O(n^2). If you are really concerned about memory allocation, well, I don't know if you realize this, but every time you call strTemp = chr + strTemp you are throwing away your old copy and building a new copy. Ouch. Forgive me for preaching, but you just committed the grievous act of premature optimization. Don't worry about that first malloc, if Python is going to call malloc, it has a lot of opportunity to do so later. And malloc isn't as evil as you make it out to be. One of the advantages of using a high level language is you get to leave the issue of how to implement the small stuff up to the language designer and focus on the bigger picture - algorithmic appropriateness and overall correctness. In my experience I've found that when under time pressure python programs tend to out perform C because doing it right is so much easier in the former. As for mutability, immutability is a big virtue and performance gain. If I have two pointers to immutable strings, once I compare them I can know for eternity which is larger, so long as I don't let go of my references to them. Thus I can use them as keys in a complicated and efficient data structure. If Python strings were mutable the best implementation we could hope for dict would be a linked list. Also, consider some other side effects of mutable strings. >> s = "Abc" >> myfancy_structre.add_somehow( s ) >> t = s[::-1] >> print s Abc >> print t cbA Now if strings were mutable: >> s = "Abc" >> myfancy_structre.add_somehow( s ) >> s.reverseme() >> print s cbA Other users of s between assignment and reversal (like myfancy_structure) might not be happy that is was reversed when they next must use it. Cheers - Adam DePrince From johnjsal at NOSPAMgmail.com Mon Mar 13 12:01:48 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 13 Mar 2006 17:01:48 GMT Subject: Environmental Variables In-Reply-To: <1142246053.485766.41280@i39g2000cwa.googlegroups.com> References: <1142246053.485766.41280@i39g2000cwa.googlegroups.com> Message-ID: <0AhRf.1777$No6.40654@news.tufts.edu> Sathyaish wrote: > In which physical file are the python environmental variables located? > I know I can access them using the: > > > os.environ.get('PYTHONSTARTUP') > > or > > os.environ.get('PYTHONPATH') > > > to get their values. But out of the program, if I need to look at them > and alter their values, where do I find them? Are they the OS > environmental variables as I suspect? If they are, then I'll find them > with the other OS environ variables in My > Computer->System->Properties->Advanced->Environmental Variables. > > But I checked that place and did not find any default values for them. > As far as PYTHONPATH goes, I added that one manually to my list of environment variables. As far as I know, it's not there by default. Now, can someone tell me if adding it manually interferes with anything else Python itself is doing? From http Wed Mar 8 03:19:55 2006 From: http (Paul Rubin) Date: 08 Mar 2006 00:19:55 -0800 Subject: cgi problem Message-ID: <7xk6b5mjpw.fsf_-_@ruckus.brouhaha.com> I'm trying to write a simple cgi that reads a post from the user's browser, does some stuff with the form data, and redirects the browser back to the originating url, i.e. I want the cgi to send a 302 redirect. There's no obvious way in the cgi module to set the response code to anything but 200. I.e. the run_cgi method automatically sends the 200 response without giving any way to suppress it (like nph-whatever in Apache). Is that a missing feature that I should add, or am I trying to do something dumb? Thanks. From uval at rz.uni-karlsruhe.de Thu Mar 16 12:41:08 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Thu, 16 Mar 2006 18:41:08 +0100 Subject: what's going on here? In-Reply-To: References: Message-ID: [...] > So finally here's my question: If you are using data.append(), doesn't > that just put all the numbers into one long list? no, append appends extend does what you think How are the tuples > still being created in this case so that the list comprehensions still > work? It seems like there is no longer any 'row' to refer to in data. why not to fire interpreter to see what happens >>> line1 = "1 2 3 4" >>> line2 = "5 6 7 8" >>> lst = [] >>> lst.append(map(float, line1.split())) >>> lst [[1.0, 2.0, 3.0, 4.0]] >>> lst.append(map(float, line2.split())) >>> lst [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]] >>> hth, Daniel From bapolis at gmail.com Wed Mar 1 06:22:52 2006 From: bapolis at gmail.com (bapolis at gmail.com) Date: 1 Mar 2006 03:22:52 -0800 Subject: pysqlite problem Message-ID: <1141212172.445009.230610@i39g2000cwa.googlegroups.com> Hello, I'm getting the following error: pysqlite2.dbapi2.OperationalError: no such table: tbl1 Here's my code: from pysqlite2 import dbapi2 as sqlite con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES) cur = con.cursor() cur.execute("select * from tbl1") data = cursor.fetchall() for record in date: record[0], record[1] my installation versions: python 2.4.2 pysqlite 2.0.7 sqlite 3.3.4 I checked to make sure I have a table called tbl1. I don't understand what's going on. Any ideas? From fredrik at pythonware.com Wed Mar 22 03:27:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Mar 2006 09:27:47 +0100 Subject: markup.py - HTML/XML generator References: <1142854029.584897.108360@i39g2000cwa.googlegroups.com> Message-ID: Gerard Flanagan wrote: > Now I can do this: > > page = HtmlPage('Test Page') > navbar = page.div(id='left').ul(css='navbar') > for href,link in {'/home':'Home', '/shop':'Shop', > '/cart':'Cart'}.iteritems(): > navbar.li.a(link,href=href) > page.div(id='main').h1('Header').p('') > > So *that's* what '__call__' does - I am enlightened! just wait until you figure out what iteritems do ;-) ::: I'm sure you already know it, but dictionaries aren't ordered, so that navigation bar may not come out as you'd expect. >>> {"/home": "Home", "/shop": "Shop", "/cart": "Cart"} {'/cart': 'Cart', '/shop': 'Shop', '/home': 'Home'} From fredrik at pythonware.com Thu Mar 30 12:29:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 30 Mar 2006 19:29:38 +0200 Subject: Set Windows Environment Variable References: <1143723906.146263.136590@i40g2000cwc.googlegroups.com> <1143737936.678171.211010@z34g2000cwc.googlegroups.com> Message-ID: Fuzzyman wrote: > I *believe* that ``SetEnvironmentVariable`` exists in the underlying > windows API, but that it isn't wrapped by the win32api extension. SetEnvironmentVariable does the same thing as assignment to os.environ. The only way to set the environment for another process is to create the process yourself, and pass in an environment block. To modify the system environment, you need to update the registry and broadcast a window message; see: http://msdn.microsoft.com/library/en-us/dllproc/base/environment_variables.asp (that cannot be used to modify the environment for arbitrary processes, though. it's up to each process to decide how to handle that message, if it cares about window messages at all). From andymac at bullseye.apana.org.au Thu Mar 2 17:16:17 2006 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Fri, 03 Mar 2006 08:16:17 +1000 Subject: Problem with dbi, odbc module and Oracle 9.2 - suffixed "L" with number data type In-Reply-To: <1141293671.315768.186560@i39g2000cwa.googlegroups.com> References: <1141293671.315768.186560@i39g2000cwa.googlegroups.com> Message-ID: <44076EB1.4050900@bullseye.apana.org.au> [posted & mailed] dananrg at yahoo.com wrote: > The only issue I've had so far is retrieving data from Oracle when an > integer has been defined like: > > number(p) [same thing as number(p,0) evidently] > > This is from a database I didn't design and can't change. Evidently > there are new ways to declare integer data types in Oracle. > > The problem is that the ODBC module suffixes an "L" to any integer > returned that > was defined as data type number(p). For example, an integer stored as: > 56 will be returned as 56L. Actually, it now seems to be doing the > same thing, at least in some cases, for number data types declared as > number(p,s). What gives? Anyone know why this would happen? The 'L' suffix indicates a Python long, which is an arbitrary precision integer. If you're confident that the number in question is in the normal integer range, you can coerce it to a normal int with int(p) so the formatting on display doesn't include the suffix - if the number is too large to coerce an OverflowError will be raised (for 2.2 and earlier at least; 2.4 and later unify ints and longs). > Can't use mxODBC because it's a commercial product and can't use > cx_oracle at the moment because I am stuck with Python 2.1 (for ESRI > geoprocessing), and there is no cx_oracle for Python 2.1 (starts with > Python 2.2 and refuses to install for 2.1). I could install a later > version of Python independently, but I need to be able to do the > geoprocessing that 2.1 allows as well as ODBC calls to Oracle all in > the same script. This means dbi,odbc seems to be my only choice. If you have access to a compiler, you may be able to build cx_Oracle for Python 2.1, but you would have to check that the code doesn't require Python 2.2 or later features. The MingW gcc package should work with Python 2.1 (which was built with VC6 as I recall). I've been bugging ESRI about upgrading, and I'm sure others have too. ------------------------------------------------------------------------- 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 duncan.booth at invalid.invalid Sat Mar 18 07:17:00 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Mar 2006 12:17:00 GMT Subject: Problem with C-API References: <441af112$0$8332$da0feed9@news.zen.co.uk> <441b1955$0$23282$db0fefd9@news.zen.co.uk> Message-ID: John Dean wrote: > Hi Duncan > > Your version of the app works apart from this part > > .... > .... > > else { > PyObject *rString = PyObject_Str(result); > if (rString==NULL) { > Py_DECREF(result); > PyErr_Print(); > return; > } > > printf( "The result is %s\n", PyString_AsString(rString)); > Py_DECREF(rString); > Py_DECREF(result); > } > } > > The result of the printf state is: "The result is None" Yes, what did you expect it to be? The result from executing the Python code was the value None. > > > result = PyRun_String("print x", Py_file_input, dict, dict); > > The above line of code displays the value returned from the title() > function. My problem is I need to be able to cature the return value > because in the real application it will be displayed in a Process Log > Widget. Also the real scripts will be much longer. > > I have not had a problem writing Python extensions, but when it comes > to embedded Python I just see how to get my code to work. > > Any further help would be greatly appreciated > If you want the value of x, then pick it out of the dictionary: { PyObject *x = PyDict_GetItemString(dict, "x"); PyObject *rString = PyObject_Str(x); printf( "x is %s\n", PyString_AsString(rString)); Py_DECREF(rString); Py_DECREF(x); } Py_DECREF(dict); // I forgot this one in my original code. If you want to embed Python though you really should look at Pyrex. Using Pyrex you can all but forget about the Python api, write a Pyrex function which is callable directly from C: it calls the Python code and returns the C values you want as a result. Also it will handle all the error checking and reference counting automatically. From sjdevnull at yahoo.com Fri Mar 3 02:37:33 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 2 Mar 2006 23:37:33 -0800 Subject: Write a GUI for a python script? In-Reply-To: <120f12cbl2qdobb@corp.supernews.com> References: <1141334921.910918.56760@i39g2000cwa.googlegroups.com> <120f12cbl2qdobb@corp.supernews.com> Message-ID: <1141371453.078958.50360@p10g2000cwp.googlegroups.com> Grant Edwards wrote: > On 2006-03-02, sjdevnull at yahoo.com wrote: > > > Note that wxWindows wraps native widgets, > > Not on Linux/KDE systems. ;) Right, I followed that with a clarification of supported systems. You can use wxwindows with gtk-qt to get a Qt-ish look, although that's not ideal. The issue with wxqt is licensing; wxWindows is open-source, but not GPL (it allows closed-source app development); gtk is LGPL'd so that's not an issue, but Qt is GPL'd. Julian Smart (wxwindows developer) contacted Troll for license clarifications but didn't get a response (or not a useful one, I can't remember the specifics). There's no ideological opposition to a qt implementation if the licensing can be resolved (indeed they're willing to work with fully closed-source toolkits, they just don't want to force application developers using their toolkit to use a particular license). From diesch at spamfence.net Fri Mar 10 13:25:12 2006 From: diesch at spamfence.net (Florian Diesch) Date: Fri, 10 Mar 2006 19:25:12 +0100 Subject: Type Hinting vs Type Checking and Preconditions References: <1141764243.936880.324240@i39g2000cwa.googlegroups.com> Message-ID: <20060310182515.399D.a.NOFFLE@dieschf.news.arcor.de> "Tom Bradford" writes: > Let me first say that I'm sure that this subject has come up before, > and so forgive me for beating a dead horse. Secondly, let me say that > Python's strength is its dynamic nature, and I don't believe that it > should ever require a precondition scaffolding. With that said, I do > believe that something like type hinting would be beneficial to the > Python community, both for tool enablement and for disambiguous > programming. > > Here is what I mean. The following function, though conventionally > indicating that it will perform a multiplication, will yield standard > Python behaviors if a string value is passed to it: > > def multiplyByTwo(value): > return value * 2 > > Passing 14 to it will return 28, whereas passing "14" to it will return > "1414". Granted, we know and accept that this is Python's behavior > when you multiply two values, but because we don't (and shouldn't have > to) know the inner workings of a function, we don't know that the types > of the values that we pass into it may adversly affect that results > that it yields. > > Now, on the other hand, if we were to introduce a purely optional type > hint to the function prototype, such as follows: > > def multiplyByTwo(value:int): > return value * 2 > > The python interpreter could do the work of casting the incoming > parameter to an int (if it is not already) before it is multipled, > resulting in the desired result or a typecasting error otherwise. > Furthermore, it could do it more efficiently than a developer having to > put conditional code at the beginning of traditionally typecasting > functions. What's the advantage? Instead of "multiplication may not do what I want with some classes" you got "casting to int may not do what I want with some classes". Passing a float now returns a much more counterintuitive result than passing a string in the old function. And it's not working anymore with classes which you can not cast to int but implement multiplication. In any case you have to document what exactly your function is doing and the user has to read this documentation. Florian -- Emacs doesn't crash! It contains very little C, so there's very little reason to have it crash. [Pascal Bourguignon in gnu.emacs.help] From nospamformeSVP at gmail.com Tue Mar 14 21:02:35 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Tue, 14 Mar 2006 21:02:35 -0500 Subject: Printable string for 'self' Message-ID: Is there a way to discover the original string form of the instance that is represented by self in a method? For example, if I have: fred = C() fred.meth(27) then I would like meth to be able to print something like: about to call meth(fred, 27) or about to call fred.meth(27) instead of: about to call meth(<__main__.C instance at 0x00A9D238>, 27) Thanks in advance, Don. From davidb at mcs.st-and.ac.uk Fri Mar 3 06:43:42 2006 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 3 Mar 2006 03:43:42 -0800 Subject: Printing a file References: <1141127321.744881.174420@i40g2000cwc.googlegroups.com> <1141298930.103477.70690@u72g2000cwu.googlegroups.com> Message-ID: <1141386222.392704.54120@z34g2000cwc.googlegroups.com> Fabian Steiner wrote: > David Boddie wrote: > > In Qt 4, the demos/textedit demo does this with a lot less code. > > > > Or are you think of something else? > > Thank you very much for this hint! Thanks to this example I was able to > print out my first pages :) That's good to hear. :-) > But some questions still remain. At the moment I am using > QSimpleRichtext and a personal HTML-File. I had a look at the > example.html of textedit.cpp (/usr/share/doc/qt-4.1.1/demos/textedit) > and found out that it contains quite a lot of proprietary HTML elements, > attributes and CSS style definitions. So far I didn't even know that > QSimpleRichText even supports CSS since I couldn't find anything related > to this point in the official docs (--> e.g. QStylesheet). I think I may have confused you by mentioning Qt 4. Since you are using QSimpleRichText, you must be using Qt 3, so you should probably ignore what I said about the /usr/share/doc/qt-4.1.1/demos/textedit demo. :-/ > Is there any tool out there with which I can write those special HTML > files? I am quite familiar with HTML and CSS but I don't want to waste > my time with that. You don't need to include all those style attributes in the HTML. Anyway, that's a different version of Qt to the one you are using, so you can safely ignore it. You should probably look at the text drawing part of the demo included in Qt 3 (examples/demo/textdrawing) and see how printing is done for the rich text editor there (in the TextEdit::filePrint() function). Translating it to Python _shouldn't_ be a problem. I hope I didn't confuse you too much by talking about two different versions of Qt at the same time. Let us know how it goes. David From nil at dev.nul Sun Mar 19 00:36:07 2006 From: nil at dev.nul (Christian Stapfer) Date: Sun, 19 Mar 2006 06:36:07 +0100 Subject: strange math? References: <1142745707.384085.42050@i39g2000cwa.googlegroups.com> Message-ID: wrote in message news:1142745707.384085.42050 at i39g2000cwa.googlegroups.com... > Hello everyone, I'm experimenting with python and i'm following this > tutorial: > http://docs.python.org/tut/node6.html#SECTION006400000000000000000 I'm > in section 4.7.5 Lambda Forms. In this section I was working along and > I noticed something strange. It happened because of a typo. Below is > a copy/paste from my idle session: > >>>>def make_incrementor(n): > return lambda x: x+n > >>>>f=make_incrementor(42) >>>>f(0) > 42 >>>>f(1) > 43 >>>>f(10) > 52 >>>>f(0) > 42 >>>>f(01) > 43 >>>>f(02) > 44 >>>>f(010) > 50 >>>>42+010 > 50 > > The first f(01) was a mistake. I accidentally forgot to delete the > zero, but to my suprise, it yielded the result I expected. So, I tried > it again, and viola, the right answer. So, I decided to really try and > throw it for a loop, f(010), and it produced 50. I expected 52 > (42+10). Why doesn't python ignore the first zero and produce a result > of 52? That's because python interprets 010 as *octal* 10 which is *decimal* 8. Thus 42+010 = 42+8 = 50 which is quite as it should be... Regards, Christian From uymqlp502 at sneakemail.com Thu Mar 9 12:20:17 2006 From: uymqlp502 at sneakemail.com (Russ) Date: 9 Mar 2006 09:20:17 -0800 Subject: implementation of "complex" type References: <1141895757.128437.159460@i39g2000cwa.googlegroups.com> Message-ID: <1141924817.076466.23680@v46g2000cwv.googlegroups.com> "Why don't you show us your complex class?" Because I don't have a complex class. I merely used the complex class as an example to test the referencing behavior. Please read more carefully next time. From deets at nospam.web.de Tue Mar 14 07:31:39 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 14 Mar 2006 13:31:39 +0100 Subject: andmap and ormap References: <1142339035.687474.271120@p10g2000cwp.googlegroups.com> Message-ID: <47nre2FgfgkkU1@uni-berlin.de> > Does python have andmap and ormap: > > andmap((lambda t: boolean(t)),L) > > gives True if boolean(t) is True for all t in L and False otherwise? > And > > ormap((lambda t: boolean(t)),L) > > gives True if boolean(t) is True for some t in L and False otherwise? > One can use a list comprehension like > > [x for x in L if not(False in map((lambda t: boolean(t)),L))] > > as an example of selection by andmap, and > > [x for x in L if (True in map((lambda t: boolean(t)),L))] > > as an example of selection by ormap. > > How does one define andmap/ormap so its first argument is a boolean > procedure or lambda? > > def andmap(b,L): > if False in map(b,L): return False > else: return True > > def ormap(b,L): > if True in map(b,L): return True > else: return False import operator reduce(operator.and_, [predcidate(o) for o in objects]) predicate can be a lambda, if it has to be. Diez From gregory.petrosyan at gmail.com Tue Mar 21 14:23:41 2006 From: gregory.petrosyan at gmail.com (Gregory Petrosyan) Date: 21 Mar 2006 11:23:41 -0800 Subject: Why "class exceptions" are not deprecated? Message-ID: <1142964085.356976.166620@t31g2000cwb.googlegroups.com> 1) From 2.4.2 documentation: There are two new valid (semantic) forms for the raise statement: raise Class, instance raise instance 2) In python: >>> raise NameError Traceback (most recent call last): File "", line 1, in ? NameError >>> help(NameError) Help on class NameError in module exceptions: ... >>> raise 0 Traceback (most recent call last): File "", line 1, in ? TypeError: exceptions must be classes, instances, or strings (deprecated), not i nt So, if it's a bug in documentation, it should be corrected. Otherwise, (IMHO!) raising classes should be deprecated. Does raising class make sence? As for me, I can't find any usefull case for it. From caleb.hattingh at gmail.com Tue Mar 28 16:26:39 2006 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 28 Mar 2006 13:26:39 -0800 Subject: Multiplying sequences with floats In-Reply-To: References: <1143239583.002604.44010@v46g2000cwv.googlegroups.com> Message-ID: <1143581199.565194.61780@i40g2000cwc.googlegroups.com> Christoph I understand the explanation regarding the underlying math.floor() call. Were I using this functionality in my code, int(a//b)* some_list would not be something I consider a big deal. However, I see what you're saying: The multiplcation by list can only work with an int, and you have an integer number, but unfortunatly with type float. Well, I guess that's life :) Again, a small cast like that is not a problem for me, so I can't really comment on this. Keep well Caleb From dw at botanicus.net Mon Mar 13 13:23:26 2006 From: dw at botanicus.net (David Wilson) Date: 13 Mar 2006 10:23:26 -0800 Subject: IOS-style command line interface module? In-Reply-To: <1142152620.547133.16970@p10g2000cwp.googlegroups.com> References: <1142123159.212193.21400@u72g2000cwu.googlegroups.com> <1142152620.547133.16970@p10g2000cwp.googlegroups.com> Message-ID: <1142274206.301584.265120@j33g2000cwa.googlegroups.com> Doh, I am indeed referring to the standard "cmd" module - thanks! To insyte at gmail.com, the above module does what you describe. Thanks again, David. From wkehowski at cox.net Thu Mar 16 12:23:46 2006 From: wkehowski at cox.net (wkehowski at cox.net) Date: 16 Mar 2006 09:23:46 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> Message-ID: <1142529826.007508.286420@i39g2000cwa.googlegroups.com> Flame war? Absolutely not. My reason is to learn. There are many sites dedicated to reasonably objective comparisons between languages. Here are two examples: http://www.smallscript.org/Language%20Comparison%20Chart.asp http://www.jvoegele.com/software/langcomp.html The wildcard exclusion problem is interesting enough to have many distinct, elegant solutions in as many languages. It would be interesting to see if they converge to roughly the same solution or if there are essential differences. And your code is a crash course in Haskell! Tossing aside the 'flame war' inquiry your code response is my only goal. I hope many others find the problem and responses as fascinating as I do. From dwahler at gmail.com Wed Mar 1 16:00:43 2006 From: dwahler at gmail.com (David Wahler) Date: 1 Mar 2006 13:00:43 -0800 Subject: Cross compile generation of .pyc from .py files... References: <1141176107.234667.93210@e56g2000cwe.googlegroups.com> <1141226105.584710.175840@j33g2000cwa.googlegroups.com> <1141234918.915386.128410@i40g2000cwc.googlegroups.com> Message-ID: <1141246843.774200.53750@i40g2000cwc.googlegroups.com> venkatbo at yahoo.com wrote: > I was under the impression, that the .pyc files will be used (if found) > by python to speed up execution of scripts... and so we packaged, > deployed and installed the .py/.pyc files on to the ppc-target system. > That package includes, site.py(c), types.py(c) etc., among others. > > Though I see these errors when I invokde 'python -v', I'm able to > execute the .py files... but was hoping to use the .pyc files to > benefit from the enhanced speed of execution. [snip...] .pyc files do not increase the speed of execution -- only the speed of importing modules. Even then, the benefit is only seen the first time the modules are loaded, as the .pyc files will be generated automatically. I'd say the tiny, one-time speedup isn't worth it; and if you really want the modules to be precompiled, it's better to do it at installation time using distutils. -- David From aleaxit at yahoo.com Sun Mar 26 10:21:23 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Mar 2006 07:21:23 -0800 Subject: Extending Methods Vs Delegates References: <1142985431.079078.3480@i40g2000cwc.googlegroups.com> <1hckjdk.c55h629l2oz8N%aleaxit@yahoo.com> <1143370158.058148.180170@v46g2000cwv.googlegroups.com> Message-ID: <1hcsoo8.16314r0vrnqpiN%aleaxit@yahoo.com> vbgunz wrote: > I am sorry I couldn't reply sooner! Alex, Python in a nutshell is my > bible and I take it virtually everywhere! Seriously, I would highly > recommend it to anyone with a little to a lot of Python experience. > > I apologize for misinterpreting your passage on page 80. I will look > much closer at your examples, links and ideas and I hope to straighten > my knowledge on the subject of delegates! > > Thank you for hinting on the "Template Method design pattern"! Sorry > for any misunderstanding! Hey, no problem -- such a misunderstanding is always a shared responsibility, and as an author I need to take my part of the blame. Unfortunately, the root issue is that more and more common, ordinary, useful English words get expropriated by specialized technical meanings, making it almost impossible to discuss technical matters in ordinary English without *some* risk of misunderstanding (by the reader mistakenly seeing a "specialized, technical meaning" where the NORMAL English use of the word, possibly in a slightly metaphorical vein, is what the author meant). From "function" and "procedure", to "delegate" and "built-in", a growing number of words become "risky"!-) Funny enough, the problem is worst in English - because in many other languages, the specialized technical terms often use borrowed English words, so the other language's native terms remain available. Latin had similar luck wrt Greek a couple millennia ago -- all technical terms of philosophy were borrowed Greek words, so the risk of confusion was in fact much lower than it was in Greek;-). Alex From deets at nospam.web.de Thu Mar 9 11:42:06 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 09 Mar 2006 17:42:06 +0100 Subject: Blocking a thread for x seconds References: Message-ID: <47b49uFeqaobU1@uni-berlin.de> Fernando Rodredguez wrote: > I have a class that descends from threading.Thread. One method should > block > the thread during x seconds and then call another method. How can I do > this? time.sleep(x) [*] * this comes witout any warranty about the slept time whatsoever under the assumption that time.sleep is not run under a RTOS with guaranteed timings Diez From bdesth.quelquechose at free.quelquepart.fr Mon Mar 20 20:29:03 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 21 Mar 2006 02:29:03 +0100 Subject: user-supplied locals dict for function execution? In-Reply-To: <1142887575.402624.156050@e56g2000cwe.googlegroups.com> References: <1142875454.906993.126370@v46g2000cwv.googlegroups.com> <441eedbd$0$20865$636a55ce@news.free.fr> <1142879594.924929.96440@v46g2000cwv.googlegroups.com> <441f0623$0$23127$626a54ce@news.free.fr> <1142887575.402624.156050@e56g2000cwe.googlegroups.com> Message-ID: <441f29ec$0$31422$626a54ce@news.free.fr> Lonnie Princehouse a ?crit : > Occaisionally, the first two lines of The Zen of Python conflict with > one another. """ Beautiful is better than ugly. Explicit is better than implicit. """ Err... I see no contradiction nor conflict here. > An API I'm working on involves a custom namespace implementation using > dictionaries, and I want a pretty syntax for initializing the custom > namespaces. The fact that these namespaces are implemented as > dictionaries is an implementation detail, and I don't want the users to > access them directly. Ok. That's effectively not a very common use case. And I agree than it's far better to abstract implementation details. (And FWIW, I still have no clean solution - but I'm not a guru). From nemesis at nowhere.invalid Sun Mar 12 06:52:20 2006 From: nemesis at nowhere.invalid (Nemesis) Date: Sun, 12 Mar 2006 11:52:20 GMT Subject: [ANN] XPN 0.5.6 Message-ID: <20060312115152.1924.40584.XPN@orion.homeinvalid> XPN (X Python Newsreader) is a multi-platform newsreader with Unicode support. It is written with Python+GTK. It has features like scoring/actions, X-Face and Face decoding, muting of quoted text, newsrc import/export, find article and search in the body, spoiler char/rot13, random taglines and configurable attribution lines. You can find it on: http://xpn.altervista.org/index-en.html or http://sf.net/projects/xpn Changes in this release: * added message-id recognition. Now XPN tries to recognize message-ids in the text and make them clickable in order to open a search window. * added a dialog window that informs you when XPN downloads new articles in watched threads. * some improvements in Global Search, now is possible to perform multiple searches. * now XPN checks if there are other istances running (it uses the file xpn.lock in the XPN directory). This behaviour should prevent database break off. * some fixes in the Score Window * fixed some bugs in header management * fixed a bug that caused crashes with multipart articles with email attached XPN is translated in Italian French and German, if you'd like to translate it in your language and you are familiar with gettext and po-files editing please contact me (xpn at altervista.org). -- No wanna work. Wanna bang on keyboard. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From reply.in.the.newsgroup at my.address.is.invalid Thu Mar 23 11:46:34 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 23 Mar 2006 17:46:34 +0100 Subject: Confused: appending to a list References: <1143131513.032932.92560@j33g2000cwa.googlegroups.com> Message-ID: DataSmash: >I'm confused. Why is it that when I say "while len(list) < 5:", I get >5 items in my list. Because the last time when len(list) was < 5, the block of code following the while executed and did something to the list to give it a length >= 5 (otherwise the block of code would be executed again and it wouldn't have been the last time). > list.append(num) There you have it. -- Ren? Pijlman Wat wil jij leren? http://www.leren.nl From jstroud at ucla.edu Sat Mar 11 17:59:05 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 11 Mar 2006 14:59:05 -0800 Subject: why "g".count('')==2 ? In-Reply-To: References: <1142079957.325348.248500@j52g2000cwj.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Sat, 11 Mar 2006 13:37:05 +0100, Fredrik Lundh wrote: > > >>"ygao" wrote: >> >> >>>my question is as title! >> >>my answer as code: >> >> >>>>>s = "g" >>>>>t = "" >>>>>s[0:0+len(t)] == t >> >>True >> >>>>>s[1:1+len(t)] == t >> >>True > > > > Or in other words, imagine that Python is walking the string looking to > match the target. The empty string matches the boundary of every character > with the next character, or in other words, for a string s of length N, > s.count('') will equal N+1. > > I'm not sure what to describe this surprising result as. It isn't a bug; > it isn't even really a gotcha. I guess the best description is that it is > just a surprising, but logical, result. Yes, but: py> "gab".split("") Traceback (most recent call last): File "", line 1, in ? ValueError: empty separator The idea is not consistent between string functions. I actually consider this latter example a bug. Jaems -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From hancock at anansispaceworks.com Mon Mar 6 16:01:35 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 6 Mar 2006 15:01:35 -0600 Subject: setting PYTHONPATH In-Reply-To: <20060306070531.50187.qmail@web50110.mail.yahoo.com> References: <20060306070531.50187.qmail@web50110.mail.yahoo.com> Message-ID: <20060306150135.54eae0e1@samwise.anansi> On Sun, 5 Mar 2006 23:05:31 -0800 (PST) anushya beauty wrote: > Anybody, please help me to set PYTHONPATH to import > my modules?. Where is sy.path set? > > In some python groups site, to import the user modules, > they explained to create one __init__.py file in my > module directory (this file should include __all__ > variable, which refer to the modules that the user > wants to import). How to set the __all__ var? PYTHONPATH is an environment variable. You set this however your operating system lets you do handle them. In Linux or Unix with csh/tcsh, this looks like: setenv PYTHONPATH /path/to/python/files in bash/sh it looks like: set PYTHONPATH=/path/to/python/files and I'm sure there's some way to do it in Windows and OS X. sys.path means "the name path in the module sys" So, in order to see that, you need to (from python): >>> import sys >>> sys.path >>> sys.path ['', '/usr/lib/python23.zip', '/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2', ...] As you can see, it's a list. You can append to it, or more likely, prepend the directory you need. __all__ is a "magic" variable in the __init__.py (or any module) which you can set to define which names will be imported when you import from that module: If module "foo.py" contains: __all__ = ['a', 'b'] a = 1 b = 2 c = 3 then another module which imports from foo will get a and b, but not c: >>> from foo import * >>> a,b (1, 2) >>> c Traceback (most recent call last): File "", line 1, in ? NameError: name 'c' is not defined Meanwhile: __init__.py This is how you make a "package" out of a directory of python modules. Its namespace is the package-wide space. So you can control what modules are loaded with explicit commands, or you can leave it empty and then you will have to do explicit imports of sub-modules: spam/ __init__.py ham.py eggs.py requires explicit imports of ham and eggs modules: >>> import spam >>> import spam.ham >>> import spam.eggs Although these things are all interesting, they are not closely related, and you haven't really said what your problem is, so I don't know which is going to be helpful to you. -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From markscala at gmail.com Fri Mar 31 16:59:26 2006 From: markscala at gmail.com (markscala at gmail.com) Date: 31 Mar 2006 13:59:26 -0800 Subject: running IDLE from another program? In-Reply-To: <442d7a45$1_2@newspeer2.tds.net> References: <442d7a45$1_2@newspeer2.tds.net> Message-ID: <1143842365.980866.133780@g10g2000cwb.googlegroups.com> what i do is open idle, import the codefile i've begun to write, and then write a function: def r(): reload(codefile) then when I want to run it after changes, I just call the function manually in idle. From aleaxit at yahoo.com Fri Mar 10 01:57:19 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Mar 2006 22:57:19 -0800 Subject: Why property works only for objects? References: Message-ID: <1hbyfme.1cul2uwko9576N%aleaxit@yahoo.com> Michal Kwiatkowski wrote: > So another question arise. Is it possible to make function a method (so > it will receive calling object as first argument)? Sure, impor types then call types.MethodType: f = types.MethodType(f, obj, someclass) (f.__get__ is also fine for Python-coded functions) -- make sure that someclass is obj's class or some ancestor of it, of course. Alex From rtilley at vt.edu Thu Mar 9 08:53:59 2006 From: rtilley at vt.edu (rtilley) Date: Thu, 09 Mar 2006 08:53:59 -0500 Subject: Python Evangelism In-Reply-To: References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> Message-ID: Steve Holden wrote: > Doug Bromley wrote: >> I can see Ruby overtaking Python if we don't ALL do something about it. I think it's the name. Python. Let's change it to something nicer. Think about it... if you found a Ruby, you'd pick it up and put it in your pocket. If you ran across a Python, you'd run away. Gems is nice too. Compare that to Cheese Shop... who came up with that :) Do you want a pretty gem stone or a smelly slice of cheese? I mean that in a literal sense. I don't think Python is smelly at all, but it certainly has chosen some slimy, smelly bad names for itself! Psychology is important. Just as important as good design. I think this fact doesn't sink in to the Python community. From hancock at anansispaceworks.com Mon Mar 13 21:34:43 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 13 Mar 2006 20:34:43 -0600 Subject: Please, I Have A Question before I get started In-Reply-To: <40l912h0aubfgai2en7n465ml9olg746h9@4ax.com> References: <40l912h0aubfgai2en7n465ml9olg746h9@4ax.com> Message-ID: <20060313203443.5bafdf91@samwise.anansi> On Mon, 13 Mar 2006 02:19:39 GMT Skipper wrote: > Basically the program will blank the screen and call up > (for example) 6 pictures. A flashing border with travel > from picture to picture. When the computer senses a mouse > click it will clear the screen and present a second set of > choices ... one level deeper than the first ... based on > the chosen picture. So the key difference from, say, a web page in a browser, is that you want the choice to be determined by timing, not by where the mouse is pointed? This is actually quite non-standard, so there won't be a lot of support for it in GUI-building tools. However, it is the sort of thing that a game toolkit is well-organized for. IMHO, PyGame is probably very close to the fastest way to achieve this. But you will have to learn how to create a data model for your menus, etc. The main module can be dead simple, though. You just need to paste in a little PyGame boilerplate at the top (examples are included in the PyGame distribution), then you'll have a loop that handles displaying a menu, rotating through the choices, and listening for keyboard input. Something like this (I'm writing from memory -- you'll have to check the pygame documentation (which is excellent, BTW) to find details): import pygame from pygame.locals import * pygame.init() screen = pygame.display.set_mode((800,600)) # There are smarter ways to do this, but for # a one-off project, just use your known screen size # HERE YOU NEED TO BUILD YOUR MENU TREE # I'm assuming a tree structure of some # kind with some obvious methods attached # to each node current_menu = root_menu while 1: current_menu.display() try: for choice in current_menu.choices: root_menu.highlight(choice) t0= pygame.time.get_ticks() t = t0 while t When interactively asking for a path on the cmdl, I'd like to go beyond just 'raw_input' and provide shell like path completion. My research has made me believe that a combination of the cmd and glob modules is what I need, but I find the doc HIGHLY unintuitive and wasn't able to come by any examples. Does anybody have a code example for something like that lying around? There's also the rlcompleter module, but in the interest of better platform agnosis I'd like to stick with cmd ... Thanks for any hints, Joh From ingmar.ko.andersson at glocalnet.net Wed Mar 15 18:58:52 2006 From: ingmar.ko.andersson at glocalnet.net (koia) Date: 15 Mar 2006 15:58:52 -0800 Subject: Excel ShapeRange problem with win32com Message-ID: <1142467132.894238.138160@i39g2000cwa.googlegroups.com> Hi, I have a problem with adding attributes to a Line in an Excel drawing using the Python win32com interface. From recording in Excel I get the Macro: Sub Makro1() ActiveSheet.Shapes.AddLine(192.75, 63.75, 316.5, 110.25).Select Selection.ShapeRange.Line.ForeColor.SchemeColor = 10 Selection.ShapeRange.Line.Visible = msoTrue End Sub I want to replicate this from Python24 using the win32com interface: import win32com.client.dynamic xlapp = win32com.client.dynamic.Dispatch("Excel.Application") xlapp.Visible = True xlbook = xlapp.Workbooks.Add() xlapp.ActiveSheet.Shapes.AddLine( 0, 0, 100, 100).Select > xlapp.Selection.ShapeRange.Line.ForeColor.SchemeColor = 10 This fails on ShapeRange, with output listed below. What can the problem be? Is there a solution/work-around? Thanks in advance /koia Traceback (most recent call last): File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp\pythonlib\dbgp\client.py", line 3180, in runcode locals = self.frame.f_locals) File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp\pythonlib\dbgp\client.py", line 1574, in runcode h_exec(code, globals=globals, locals=locals, module=module) File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp\pythonlib\dbgp\client.py", line 516, in __init__ exec code in globals, locals File "", line 0, in __main__ File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 489, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: .ShapeRange From sybrenUSE at YOURthirdtower.com.imagination Wed Mar 22 12:38:41 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 22 Mar 2006 18:38:41 +0100 Subject: Need help with restricting number of new objects a user script can create References: <1143047823.130502.267140@t31g2000cwb.googlegroups.com> Message-ID: vj enlightened us with: > how do I restrict the user from (inadvertently or maliciously) > creating a large number of objects which will bring down the entire > 100 nodes. Use ulimit to give them a limited amount of CPU time, memory etc. The kernel will then kill runaway processes. 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 aleaxit at yahoo.com Thu Mar 9 10:19:37 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 9 Mar 2006 07:19:37 -0800 Subject: advice on this little script References: <2bSdncqWK7aJN5LZRVn-vA@rcn.net> <1hbwk99.18v8n9h1o5wj4N%aleaxit@yahoo.com> <44101098_1@newspeer2.tds.net> Message-ID: <1hbx84a.nu95v1qqm0n1N%aleaxit@yahoo.com> Kent Johnson wrote: ... > If you use from xx import yy, searching for yy will show you its > provenance as well. But when seeing the barename yy, it gives no clue whether the module you're reading used 'from xx import yy' or defined yy in any other way (localy, globally, or in any intermediate scope). 'from' has many other disadvantages, such as working badly with reload _except_ when used specifically to import a module. Alex From vbgunz at gmail.com Sun Mar 5 09:14:46 2006 From: vbgunz at gmail.com (vbgunz) Date: 5 Mar 2006 06:14:46 -0800 Subject: Argument Precedence (possible bug?) References: <1141562380.331820.42260@i40g2000cwc.googlegroups.com> <1141562704.979483.63730@i40g2000cwc.googlegroups.com> Message-ID: <1141568086.372615.155760@t39g2000cwt.googlegroups.com> Please allow me some time to look at your examples. I get hung up over the smallest details because in my mind, my approach should have just worked... I learned about these parameters reading "O'reilly Learning Python 2nd Edition". On page 217 of the paperback or Chapter 13.5.6 in the ebook, topic: 'Argument matching: The Gritty Details' mentions the following in verbatim... ...''' Moreover, Python internally carries out the following steps to match arguments before assignment: 1. Assign non-keyword arguments by position. 2. Assign keyword arguments by matching names. 3. Assign extra non-keyword arguments to *name tuple. 4. Assign extra keyword arguments to **name dictionary. 5. Assign default values to unassigned arguments in header. '''... As you can probably tell, I tried to follow the steps exactly, except step 5 got me lost so I tried not to question it. Anyhow, thank you very much for your time and examples. I will get back to you as soon as I am done putting your response to trial. Thank you! From grante at visi.com Wed Mar 29 10:06:41 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 29 Mar 2006 15:06:41 -0000 Subject: pySerial: write in a blocking mode References: <1143578747.023574.150300@i39g2000cwa.googlegroups.com> <122jiieidb70q2b@corp.supernews.com> <1143620378.652598.301110@j33g2000cwa.googlegroups.com> Message-ID: <122l8k1pjc2uf49@corp.supernews.com> On 2006-03-29, pdalet wrote: > The best solution is to send the last character with > interrupt. when the TDR is empty an interrupt is generated. An > interrupt program is executed to change the state of dtr. No. That doesn't work. You have to wait until the transmit _shift_register_ is empty, not the transmit data register. If you shut off DTR as soon as the transmit data register is empty, you'll cut off the last character. The transmit data register will go empty as soon as the last byte has been loaded into the shift register. At that point the last byte hasn't been sent yet. And on the 16450 and 16550 UARTS there _is_no_interrupt_ for transmit shift register empty. Even if you poll for the shift register empty status bit, some implimentations set that bit too early and you'll cut off part or all of the last stop bit. Trust me. I've fought with this issue on PCs for 15 years. -- Grant Edwards grante Yow! But was he mature at enough last night at the visi.com lesbian masquerade? From tomasz.zielonka at gmail.com Thu Mar 16 09:38:50 2006 From: tomasz.zielonka at gmail.com (Tomasz Zielonka) Date: Thu, 16 Mar 2006 14:38:50 +0000 (UTC) Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> Message-ID: Tomasz Zielonka wrote: > putStrLn (concat (intersperse " " ["generateMatching", show a, show b, show c])) Minor correction: it should be "generateNotMatching". Best regards Tomasz -- I am searching for programmers who are good at least in (Haskell || ML) && (Linux || FreeBSD || math) for work in Warsaw, Poland From jparlar at cogeco.ca Thu Mar 16 21:58:13 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Thu, 16 Mar 2006 18:58:13 -0800 Subject: TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple' In-Reply-To: References: Message-ID: On Mar 16, 2006, at 3:14 PM, Peter Bismuti wrote: > Can anyone explain this error message?? > > Traceback (most recent call last): > ? File "/acct/pjb9508/RAT/Scripts/PyQt/RatDialog.py", line 30, in > NewClipButton_clicked > ??? > self.rat.planeClip(self.o,"SQUARE"+str(self.squareCounter),width,origin > ) > ? File "/acct/pjb9508/RAT/Scripts/PyQt/rat.py", line 12, in planeClip > ??? plane1[1] = origin[1]-width > TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple' > > It looks like origin[1] and 'width' are both tuples. Substraction is not defined on tuples. That's what the error message is saying at least: "TypeError: unsupported operand type(s) for -:" -This means that the '-' operator received some bad types, types it doesn't know how to work with "'tuple' and 'tuple'" - This means the two types it received were both tuples. Jay P. From deets at nospam.web.de Fri Mar 17 12:33:34 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 17 Mar 2006 18:33:34 +0100 Subject: Problem with C-API References: <441af112$0$8332$da0feed9@news.zen.co.uk> Message-ID: <480a7gFhgefjU1@uni-berlin.de> John Dean wrote: > Hi > > I spent the whole of yesterday trying the get the following C code to > execute > > PyRun_String("def title();", Py_file_input, dict, dict); ^^^^^^^^^^^ Try using a colon here.... > PyRun_String("\treturn 'Foo Bar'", Py_file_input, dict, dict); > PyRun_String("x = title()", Py_file_input, dict, dict); > PyObject * result = PyRun_String("print x", Py_file_input, dict, dict); > printf( "The result is %s\n", PyObject_AsString( result ); Overall it seems to me that ther must be a better way to do such a thing - even in C. AFAIK it supports multiline-stringliterals. Why don't you do something like this: script = "\ def foo():\n\ return 'FooBar'\n\ x = title()\n\ print x\n" And then read that script line by line, feeding it to the parser. Or maybe the parser even groks that string at once - don't know that. Diez From gene.tani at gmail.com Fri Mar 31 15:12:52 2006 From: gene.tani at gmail.com (gene tani) Date: 31 Mar 2006 12:12:52 -0800 Subject: how to comment lot of lines in python In-Reply-To: <1143760897.940841.285300@i39g2000cwa.googlegroups.com> References: <1143760897.940841.285300@i39g2000cwa.googlegroups.com> Message-ID: <1143835972.204279.299460@i40g2000cwc.googlegroups.com> diffuser78 at gmail.com wrote: > Like in C we comment like > /* > Bunch of lines of code > */ > scite has a feature where you modify your delimiter in block comments, i.e. what comes after "#" http://scintilla.sourceforge.net/SciTEDoc.html From bill.scherer at verizonwireless.com Thu Mar 2 13:47:32 2006 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Thu, 02 Mar 2006 13:47:32 -0500 Subject: how do you move to a new line in your text editor? In-Reply-To: <78E6A2FC276AD8428A8E2DBBB540855E03BFC3E7@NYOBGCEXMB21.uswin.ad.vzwcorp.com> References: <78E6A2FC276AD8428A8E2DBBB540855E03BFC3E7@NYOBGCEXMB21.uswin.ad.vzwcorp.com> Message-ID: <44073DC4.6010302@verizonwireless.com> John Salerno wrote: > This is a real small point, but I'd like to hear what others do in this > case. It's more an 'administrative' type question than Python code > question, but it still involves a bit of syntax. > > One thing I like to do is use tabs for my indentation, because this > makes it easy to outdent when I need to start a new line in column 1. I > can press backspace once and move 4 spaces to the left. > > But I read in the PEP that spaces are recommended over tabs. If this is > the case, it would involve pressing backspace 4 times (or 8, etc.) to > get back to column 1. > > So I'm wondering, how do you all handle moving around in your code in > cases like this? Is there some sort of consistency to these things that > you can write rules for your text editor to know when to outdent? It > doesn't seem like you can do this reliably, though. > We usually handle this by using an editor that "knows" Python. There are many. See http://wiki.python.org/moin/PythonEditors > -- > http://mail.python.org/mailman/listinfo/python-list > From martin at v.loewis.de Mon Mar 20 16:38:19 2006 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Mon, 20 Mar 2006 22:38:19 +0100 Subject: why isn't Unicode the default encoding? In-Reply-To: References: Message-ID: <441F20CB.6030700@v.loewis.de> John Salerno wrote: > Robert Kern wrote: > >> http://www.joelonsoftware.com/articles/Unicode.html > > That was fascinating. Thank you. So as it turns out, Unicode and UTF-8 > are not the same thing? Am I right to say that UTF-8 stores the first > 128 Unicode code points in a single byte, and then stores higher code > points in however many bytes they may need? If so, I guess I had been > mislead by the '8' in the name, thinking that UTF-8 was another way of > storing characters in one byte (which would make it no different than > Latin-1, I suppose). That's all correct, except for the last parenthetical remark: using a single-byte character set isn't the same as using Latin-1. There are various single-byte characters sets; they have names like Latin-2, Latin-5, Latin-15, KOI8-R, CP437, windows-1252, and so on. Regards, Martin From paddy3118 at netscape.net Fri Mar 24 01:15:06 2006 From: paddy3118 at netscape.net (Paddy) Date: 23 Mar 2006 22:15:06 -0800 Subject: RELEASED Python 2.4.3, release candidate 1 In-Reply-To: References: Message-ID: <1143180905.948803.38490@i40g2000cwc.googlegroups.com> I just Googled and found the Python-Dev thread 'About "Coverity Study Ranks LAMP Code Quality" '. I was heartened by the type of issues raised in the discussion - it leaves me content with whats 'under-the-hood' in Python. You maintainers don't seem to bang your own drum, which is a good thing, but since I'm not a maintainer, I'd just like to roll out the drums (http://www.yakudo.com/) and shout THANKS GUYS - IT'S APPRECIATED! (boy am I gonna get it for this post :-) From phpbird at gmail.com Fri Mar 10 07:50:25 2006 From: phpbird at gmail.com (JuHui) Date: 10 Mar 2006 04:50:25 -0800 Subject: how to validate a proxy is alive? In-Reply-To: References: <1141994373.525265.165060@i39g2000cwa.googlegroups.com> Message-ID: <1141995025.458112.103900@e56g2000cwe.googlegroups.com> I want to get a html page content via a http proxy. befor this, I want to check the proxy. how to validate it? thanks From http Mon Mar 13 16:20:13 2006 From: http (Paul Rubin) Date: 13 Mar 2006 13:20:13 -0800 Subject: Is this possible in Python? References: <1142238871.199749.243470@p10g2000cwp.googlegroups.com> <1142282467.270698.142780@p10g2000cwp.googlegroups.com> <4415daf9$1_3@newspeer2.tds.net> <1142284706.609161.128540@e56g2000cwe.googlegroups.com> Message-ID: <7xbqwaavoy.fsf@ruckus.brouhaha.com> alainpoint at yahoo.fr writes: > I don't want a better way, i just want a solution to the problem as > described! I once did something like: try: raise ValueError except ValueError, e: pass then get the traceback object out of e, and snarf the relevant source line as mentioned before. From dinko.tenev at gmail.com Thu Mar 23 05:47:52 2006 From: dinko.tenev at gmail.com (Dinko Tenev) Date: 23 Mar 2006 02:47:52 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <1143024937.827420.104100@i39g2000cwa.googlegroups.com> <20060322141400.1A00.1.NOFFLE@dthierbach.news.arcor.de> Message-ID: <1143110872.284192.325230@u72g2000cwu.googlegroups.com> Dirk Thierbach wrote: > If more time during preprocessing is allowed, another idea is to > treat the wildcard expressions as regular expressions, convert > each into a finite state machine, construct the "intersection" of > all these state machines, minimize it and then swap final and non-final > states. Given the requirements, did you mean taking the *union* and swapping states? Or maybe swapping states first, and then taking the intersection? > Then you can use the resulting automaton to efficiently > enumerate S^n - W. In the above case, the resulting FSM would have just > three states. I don't see immediately how exactly this is going to work. Unless I'm very much mistaken, a FSA in the classical sense will accept or reject only after the whole sequence has been consumed, and this spells exponential times. For improved asymptotic complexity in this case, you need to be able to at least reject in mid-sequence, and that calls for a slightly different concept of a FSA -- is this what you meant? Cheers, Dinko From skip at pobox.com Sat Mar 4 23:20:49 2006 From: skip at pobox.com (skip at pobox.com) Date: Sat, 4 Mar 2006 22:20:49 -0600 Subject: A simple question In-Reply-To: <1141531294.575847.273330@j33g2000cwa.googlegroups.com> References: <1141531294.575847.273330@j33g2000cwa.googlegroups.com> Message-ID: <17418.26401.559797.185306@montanaro.dyndns.org> >>> x=[[0]*2]*2 This replicates the references. It doesn't copy objects. This short transcript demonstrates that concept: >>> x = [[0, 0], [0, 0]] >>> map(id, x) [16988720, 16988160] >>> y = [[0]*2]*2 >>> y [[0, 0], [0, 0]] >>> map(id, y) [16988520, 16988520] The object x refers to is a list with references to two other lists. The object y refers to is a list with two references to the same list. Skip From michaeltaft at gmail.com Sun Mar 12 16:05:21 2006 From: michaeltaft at gmail.com (mwt) Date: 12 Mar 2006 13:05:21 -0800 Subject: Help Create Good Data Model References: <1142107183.358685.266440@i39g2000cwa.googlegroups.com> <1142115988.067193.239570@i39g2000cwa.googlegroups.com> <1142123948.052804.5450@i40g2000cwc.googlegroups.com> Message-ID: <1142197521.068087.72040@v46g2000cwv.googlegroups.com> I get what you're saying fumanchu (or should I say Robert?). I've been working and reworking this code. It's in a lot better shape now (although I hestitate to keep flooding the conversation with each iteration of the file). At the level this app should be operating, I doubt I'll hit performance issues, and it's good to learn the basics first. However, I doubt this would scale very well, so the next step will be to educate myself aobut the performance-enhancing alternatives you're talking about. One thing I'm still not sure about -- and I suspect that there is no right answer -- is the fact that although I am writing the code in Python, the idiom is purely Java. Having my data bucket in the form of, essentially, a bean with setters and getters, and each method surrounded by (the Python version of) a "synchronized" piece, and so on all comes from my Java background. It's ending up working well as code (I'm a lot further along today), and it's accomplishing the decoupling of front and back end I was looking for, so that's excellent. However I do have the vague feeling that I am doing the equivalent of, say, writing Greek hexameters in English (i.e. it works but it is stylistically clunky). Anyway, thanks for your insight. I will probably be posting more of the code later, if you are interested in checking it out. The app is a Folding at Home client monitor (for Gnome) -- one of those applications, like a web spider, that lots of people want to create, even though there are already a zillion perfectly working versions out there. It's just about the right level of complexity for me now. mwt (Michael Taft) From oliphant.travis at ieee.org Fri Mar 3 21:06:13 2006 From: oliphant.travis at ieee.org (Travis Oliphant) Date: Fri, 03 Mar 2006 19:06:13 -0700 Subject: Comments sought for PEP 357 --- allowing any object in slice syntax Message-ID: This post is to gather feedback from the wider community on PEP 357. It is nearing the acceptance stage and has previously been discussed on python-dev. This is a chance for the wider Python community to comment on the proposal. You will find the PEP attached -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: pep-0357.txt URL: From __peter__ at web.de Thu Mar 16 09:45:50 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 16 Mar 2006 15:45:50 +0100 Subject: bisect and Queue modules in Python 2.4 References: Message-ID: SA Trygubenko wrote: > q.queue used to be a list, and now it is something else? > > I was using bisect module to implement min priority queue, as described > in python library reference (see > http://www.python.org/doc/2.3.5/lib/bisect-example.html). I have found > out that in Python 2.4 q.queue does not support "insert" anymore, which > breaks bisect. Please help! class PriorityQueue(Queue.Queue): def _put(self, item): bisect.insort(self.queue, item) def _init(self, maxsize): self.maxsize = maxsize self.queue = [] def _get(self): return self.queue.pop(0) or somesuch might work. Peter From ram0812 at hotmail.com Wed Mar 15 15:48:49 2006 From: ram0812 at hotmail.com (Raja Raman Sundararajan) Date: 15 Mar 2006 12:48:49 -0800 Subject: MS word document generator In-Reply-To: <441873b2$0$1337$8fcfb975@news.wanadoo.fr> References: <1142413907.226088.190740@j33g2000cwa.googlegroups.com> <441873b2$0$1337$8fcfb975@news.wanadoo.fr> Message-ID: <1142455729.303313.34210@j52g2000cwj.googlegroups.com> Hi Michel, Well, Office 12 will have very many features. Thats true. But my document needs to work in all versions of Office. I hope that pyRtf generated file is fully rtf compatible. :-) But so far I think it is quite okay. To answer my first question: > 1. do an align right of contents inside a cell Its not possible by speficying alignment in the Cell instance However, if you really want this feature then create a Paragraph and then set alignment=2 for the ParagraphPropertySet object Snippet: p = Paragraph( ss.ParagraphStyles.Normal, ParagraphPS(alignment=2) ) p.append() c1 = Cell(p) I need to fiddle around with the RTF to see if I can implement coloring of Cells :-) /R From gherron at islandtraining.com Fri Mar 3 14:44:49 2006 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 03 Mar 2006 11:44:49 -0800 Subject: forcing exceptions In-Reply-To: References: Message-ID: <44089CB1.9010707@islandtraining.com> Nikola Skoric wrote: >Is there a way to tell the interpreter to display exceptions, even those >which were captured with except? > > > Yes, sort of ... You have to trigger the display yourself within the capturing "except" -- it's not automatic. The traceback module provides a number of functions that can be used to display a traceback of the current (or any other) exception. In addition, it can produce a traceback of the current state of the execution stack even without an exception: Example (type this into the Python interpreter): import traceback try: assert False except: traceback.print_exc() and you'll get a traceback (a very short one in this case): Traceback (most recent call last): File "", line 2, in ? AssertionError Gary Herron From bencvt at gmail.com Sun Mar 26 03:11:08 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 26 Mar 2006 00:11:08 -0800 Subject: adding a new line of text in Tk In-Reply-To: References: Message-ID: <1143360668.216515.265380@t31g2000cwb.googlegroups.com> nigel wrote: > w =Label(root, text="Congratulations you have made it this far,just a few more > questions then i will be asking you some") > > The problem i have is where i have started to write some text"Congratulations > you have made it this far,just a few more questions then i will be asking you > some") > I would actually like to add some text but it puts it all on one line.I would > like to be able to tell it to start a new line. Just use \n in your string, e.g.: w = Label(root, text="Line 1\nLine 2\nLine 3") Or a triple-quoted string will do the trick: w = Label(root, text="""Line 1 Line 2 Line 3""") --Ben From nick-news at net4u.hr Fri Mar 3 15:31:58 2006 From: nick-news at net4u.hr (Nikola Skoric) Date: Fri, 3 Mar 2006 21:31:58 +0100 Subject: forcing exceptions References: <7xd5h3pas7.fsf@ruckus.brouhaha.com> Message-ID: In article <7xd5h3pas7.fsf at ruckus.brouhaha.com>, Paul Rubin says... > Nikola Skoric writes: > > Is there a way to tell the interpreter to display exceptions, even those > > which were captured with except? > > Normally you wouldn't do that unless you were trying to debug the > interpreter itself. It uses caught exceptions for all sorts of things > that you probably don't want displayed. I think even ordinary loop > termination may be implemented using exceptions. Yes, thanks for your quick responses, all three. You're right, I don't want to debug python :-) But I figured out that I don't need captured exceptions, the thing is that I just didn't belive the problem was that obvious. In fact, problem was in the except block, not in it's try block. The except block had this inocent statement: print self.sect[1].encode('utf-8') Which results in: Traceback (most recent call last): File "AIDbot2.py", line 238, in ? bot.checkNominations() File "AIDbot2.py", line 201, in checkNominations if sect.parseSect() == 1: File "AIDbot2.py", line 96, in parseSect print self.sect[1].encode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 15: ordinal not in range(128) Now, who can it complain about 'ascii' when I said loud and clear I want it to encode the string to 'utf-8'??? Damn unicode. -- "Now the storm has passed over me I'm left to drift on a dead calm sea And watch her forever through the cracks in the beams Nailed across the doorways of the bedrooms of my dreams" From fengk at wharton.upenn.edu Tue Mar 14 01:43:40 2006 From: fengk at wharton.upenn.edu (Kevin Feng) Date: Tue, 14 Mar 2006 01:43:40 -0500 Subject: Basic python help Message-ID: I have the following simple html file that is trying to send data to a python script, however, I am getting a weird server error: This is my HTML:
Ticker 1
This is my Python: #!/usr/bin/python import cgi print "Content-type: text/html" print form = cgi.FieldStorage() print form.keys() print "
" for x in form.keys(): print "%s=%s" % (x, form[x].value) + "
" This is my error Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, root at localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error. More information about this error may be available in the server error log. Any suggestions? Much thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjw at sympatico.ca Thu Mar 9 13:14:18 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 09 Mar 2006 13:14:18 -0500 Subject: using PyShell, or other shells? In-Reply-To: References: Message-ID: John Salerno wrote: > I'm interested in trying out shells other than IDLE, and I found > PyShell, but I'm not sure how to get it exactly. Is there a way to get > it without installing wxPython, or is it a part of it? I can't find much > reference to it in any of the manuals at wxpython.org (except for a > brief description of what it is, but not *where* it is or how to use it). > > Thanks. And if there are other shells that are newer/better, I'd > appreciate a recommendation. If you are looking for an IDE, you might consider PyScripter. http://mmm-experts.com/Products.aspx?ProductId=4 Colin W. From peter at engcorp.com Sat Mar 4 19:22:00 2006 From: peter at engcorp.com (Peter Hansen) Date: Sat, 04 Mar 2006 19:22:00 -0500 Subject: spliting on ":" In-Reply-To: References: <1141491273.776287.66070@j33g2000cwa.googlegroups.com> Message-ID: Cyril Bazin wrote: > Ok, ok, there was a mistake in the code. > (Of course, it was done on prupose in order to verify if everybody is > aware ;-) > I don't know why it is preferable to compare an object to the object > "None" using "is not". > "==" is, IMHO, more simple. Simple is better than complex.. So I use "==". The archives could tell you more, but basically on is usually interested in *identity* with a singleton object (None), not in whether the object on is examining happens to compare equal. A custom object could be designed to compare equal to None in certain cases, even though it *is not* None, leading to the "== None" approach being defective code. In the specific code in question, it won't make any differences, but I pointed it out to help folks who don't know this to start developing the safer habit, which is always to use "is" and "is not" with None (or, generally, with other singletons). > The correct program is: > > import urllib2 > for line in open("fileName.txt"): > addr, port = urllib2.splitport (line) > print (port == None) and '' or port Nope, sorry... the point is that the "and/or" pseudo-ternary operator is inherently flawed if the operand after "and" evaluates False. Check this out: >>> port = None >>> print (port == None) and '' or port None >>> print (port != None) and '' or port None and even: >>> print (port is None) and '' or port None So the bug isn't in using "!=" instead of "==", or using equality instead of identity comparison, it is in trying to use the and/or expression for a purpose it wasn't intended for. > or > > import urllib2 > for line in open("fileName.txt"): > addr, port = urllib2.splitport(line) > if port == None: > print '' > else: > print port That should work nicely... and it's more readable too! Note that in Python 2.5 you should be able to write this as print '' if port is None else port or print '' if (port is None) else port but it's quite arguable whether that is better than the simple if/else statement in this case. -Peter From bignose+hates-spam at benfinney.id.au Wed Mar 22 18:02:17 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 23 Mar 2006 10:02:17 +1100 Subject: years later DeprecationWarning References: <874q1qp51b.fsf@jidanni.org> Message-ID: <87fylaozgm.fsf@rose.polar.local> Dan Jacobson writes: > Here's the deal: I have to maintain this long gone guy's programs and > lately they've been saying > ./north_pass.py:14: DeprecationWarning: integer argument expected, got float > fl=range(1000*(math.floor(25000*f2m/1000)),46000*f2m,1000) You haven't shown us the value of all the terms there; specifically, we don't know what value has been bound to 'f2m'. Ideally, this code would have been written to be more easily readable and explicit. This is an illustration that it's never too late to do so, and that it can help you understand what the heck is going wrong. Replace those literals with named constants, that indicate what the heck they are. import math f2m = 1.0 # assuming this is where the float value gets introduced some_increment_thing = 1000 some_starting_count = 25 some_ending_count = 46 some_starting_scale = some_starting_count * some_increment_thing some_ending_scale = some_ending_count * some_increment_thing fl = range(some_increment_thing*(math.floor(some_starting_scale*f2m/some_increment_thing)), some_ending_scale*f2m, some_increment_thing) Use names that make sense in the problem domain, of course. The idea is to not keep the reader (that's you, months or years from now) guessing why '1000' is used three times, or whether it's mere coincidence that all the other values seem to be multiples of 1000, or whether each of those 1000s is meant to be the same thing, or whether one of them can change, etc. Split out this mess into separate operations, so you can see what's failing. range_start = some_increment_thing * math.floor(some_starting_scale*f2m/some_increment_thing) range_limit = some_ending_scale * f2m fl = range(range_start, range_limit, some_increment_thing) That will get you closer to the point of knowing what's causing the error. It will also (if you've chosen meaningful names) make the code much more understandable; and perhaps even give you ways to re-think the algorithm used. > (That long-gone guy is actually me, according to the notes in the > program. However those brain cells are long gone now, so it might > as well not be me.) One should always write code for some unknown future person, months or years after the original context of the problem is forgotten, to understand, without the benefit of your explanation. As you've found, that person is most frequently oneself. -- \ "Friendship is born at that moment when one person says to | `\ another, 'What! You too? I thought I was the only one!'" -- | _o__) C.S. Lewis | Ben Finney From jack at performancedrivers.com Wed Mar 1 15:47:09 2006 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 1 Mar 2006 15:47:09 -0500 Subject: Proper class initialization In-Reply-To: References: Message-ID: <20060301204709.GB14953@performancedrivers.com> On Wed, Mar 01, 2006 at 09:25:36PM +0100, Christoph Zwerschke wrote: > Usually, you initialize class variables like that: > > class A: > sum = 45 > > But what is the proper way to initialize class variables if they are the > result of some computation or processing as in the following silly > example (representative for more: > > class A: > sum = 0 > for i in range(10): > sum += i > > The problem is that this makes any auxiliary variables (like "i" in this > silly example) also class variables, which is not desired. > > Of course, I could call a function external to the class > > def calc_sum(n): > ... > > class A: > sum = calc_sum(10) > > But I wonder whether it is possible to put all this init code into one > class initialization method, something like that: Yes, it is called a meta class. > class A: > > @classmethod > def init_class(self): > sum = 0 > for i in range(10): > sum += i > self.sum = sum > > init_class() > > However, this does not work What we normally think of as an instance is an instance of a class. Classes are actually instances of metaclasses. What you are looking for is __init__, but not the __init__ defined after 'class A...' you want the __init__ that is called when you type 'class A....' Python 2.4.1 (#2, Mar 30 2005, 21:51:10) [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class MyMeta(type): ... def __init__(cls, *ignored): ... cls.sum = 0 ... for (i) in range(10): ... cls.sum += i ... >>> class A(object): ... __metaclass__ = MyMeta ... >>> print A.sum 45 >>> print A.i Traceback (most recent call last): File "", line 1, in ? AttributeError: type object 'A' has no attribute 'i' >>> For something as simple as this example it is easier and cleaner to move the loop into a function and do the one-liner assignment. Because the metaclass can do _anything_ to the class the reader is obliged to go read its code. The simple assignment from a function obviously has no side effects. Hope that helps, -jackdied From dabbaking at gmail.com Sat Mar 18 21:42:13 2006 From: dabbaking at gmail.com (Dave) Date: 18 Mar 2006 18:42:13 -0800 Subject: Getting .NET SDK to work with Python 2.4.2 In-Reply-To: <735p1212iukkvlfgh5940edsbo49v7va1n@4ax.com> References: <1142721716.734835.157980@z34g2000cwc.googlegroups.com> <735p1212iukkvlfgh5940edsbo49v7va1n@4ax.com> Message-ID: <1142736133.601131.253930@e56g2000cwe.googlegroups.com> yea i have .net 1.1, but not the sdk. do i need the 1.1 SDK too? From richardblackwood at cloudthunder.com Mon Mar 6 12:28:50 2006 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Mon, 6 Mar 2006 12:28:50 -0500 Subject: Simulation Programming Skills and Python In-Reply-To: <1141664719.527273.190710@u72g2000cwu.googlegroups.com> References: <1141664719.527273.190710@u72g2000cwu.googlegroups.com> Message-ID: Okay, I really like that analogy. Not everything a carpenter can do requires an architect to draw up a blueprint though. For example, if I tell a carpenter I want a tree house with built-in seating and a window in the roof, no other requirements, can't they figure out how to do that on their own? So I then ask, what is a "good description"? Also, can't a model be well thought-out but not necessarily designed in a way compatible with the process of translation into code? Thanks Lonnie. On 6 Mar 2006 09:05:19 -0800, Lonnie Princehouse wrote: > > Object oriented languages lend themselves fairly well to this sort of > modeling, and a strong programmer in any language should be able to > take a good description of a well thought-out model and write some code > for it. > > However, by far the harder part is designing a good model. Asking > whether all programmers are capable of that is sort of like asking > whether all carpenters are architects. > > As for Python, it's a good language for prototyping. The development > cycle moves very fast, so one can experiment with many different ideas > more quickly than in Java or C++. The price, however, is execution > speed. There are extension modules like the scipy suite which can > reclaim some lost speed, but Python will generally be slower than > compiled languages. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent at kentsjohnson.com Mon Mar 13 13:53:22 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 13 Mar 2006 13:53:22 -0500 Subject: trying to find repeated substrings with regular expression In-Reply-To: <1142272818.513560.198880@e56g2000cwe.googlegroups.com> References: <1142272818.513560.198880@e56g2000cwe.googlegroups.com> Message-ID: <4415bab8$1_2@newspeer2.tds.net> Robert Dodier wrote: > Hello all, > > I'm trying to find substrings that look like 'FOO blah blah blah' > in a string. For example give 'blah FOO blah1a blah1b FOO blah2 > FOO blah3a blah3b blah3b' I want to get three substrings, > 'FOO blah1a blah1b', 'FOO blah2', and 'FOO blah3a blah3b blah3b'. > > I've tried numerous variations on '.*(FOO((?!FOO).)*)+.*' > and everything I've tried either matches too much or too little. FOO(.*?)(?=FOO|$) > I've decided it's easier for me just to search for FOO, and then > break up the string based on the locations of FOO. Use re.split() for this. Kent From robert.kern at gmail.com Sun Mar 5 00:17:46 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 04 Mar 2006 23:17:46 -0600 Subject: Python advocacy in scientific computation In-Reply-To: <4409D3E8.9050006@bryant.edu> References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> <4409D3E8.9050006@bryant.edu> Message-ID: Brian Blais wrote: > here, I've found python to be good, but not great. matplotlib (pylab) is a really > great thing, but is not as straightforward as plotting in Matlab. Either, you have a > window which locks the process until you close it, or you do interactive mode, but > the window results disappear if any other window is put on top (like your shell), and > has to be manually redrawn. This makes it far less convenient to deal with in > interactive mode. All I can say is that I've never seen anything like that behavior. Are you tried using ipython in pylab mode? -- Robert Kern robert.kern at gmail.com "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From johnjsal at NOSPAMgmail.com Tue Mar 7 11:44:35 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 07 Mar 2006 16:44:35 GMT Subject: inserting into a list In-Reply-To: <475qs4Fdp9mhU1@uni-berlin.de> References: <475qs4Fdp9mhU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Why don't you just _try_ that? It would have been way faster than to ask > questions you can easily answer yourself. I did try it, but I was still hoping for an explanation, which I've also gotten from you guys, some in nicer terms than others. From frank at chagford.com Mon Mar 13 05:53:00 2006 From: frank at chagford.com (Frank Millman) Date: 13 Mar 2006 02:53:00 -0800 Subject: SSL/TLS - am I doing it right? In-Reply-To: References: <1142240607.501914.4390@j52g2000cwj.googlegroups.com> Message-ID: <1142247180.180132.256110@v46g2000cwv.googlegroups.com> Sybren Stuvel wrote: > Frank Millman enlightened us with: > > while 1: > > conn,addr = s.accept() > > c = TLSConnection(conn) > > c.handshakeServer(certChain=certChain,privateKey=privateKey) > > data = c.recv(1024) > > It's nice that you set up a TLS connection, but you never check the > certificate of the other side for vality. You should make sure the > certificate chain is completely signed from top to bottom. Then check > that the bottom certificate is amongst trusted CAs. Also check all the > certificates in the chain against the CRL of the CA. Thanks for the reply, Sybren. I was hoping to avoid this step. The point of the exercise for me is encryption. I am not too worried about authentication. The next step in my app is for the client to enter a user id and password, and the server will not proceed without verifying this. However, I realise that security is not something to be trivialised, so if your recommendation is that I do complete the validation steps, I will try to understand that part of the documentation and apply that as well. Thanks Frank From abbi_0382 at yahoo.com Fri Mar 3 06:07:32 2006 From: abbi_0382 at yahoo.com (anushya beauty) Date: Fri, 3 Mar 2006 03:07:32 -0800 (PST) Subject: relocate python compiled file Message-ID: <20060303110732.48257.qmail@web50111.mail.yahoo.com> Hi, When i run the python file, the python compiled file is created. Is it possible to relocate the python compiled file to some other directory?. Is it possible to frequent update the relocated pyc file while running the py file? thanks and regards, abbi --------------------------------- Yahoo! Mail Bring photos to life! New PhotoMail makes sharing a breeze. -------------- next part -------------- An HTML attachment was scrubbed... URL: From qrczak at knm.org.pl Thu Mar 16 18:21:25 2006 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Fri, 17 Mar 2006 00:21:25 +0100 Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> Message-ID: <8764medlhm.fsf@qrnik.zagroda> "wkehowski at cox.net" writes: > The python code below generates a cartesian product subject to any > logical combination of wildcard exclusions. For example, suppose I want > to generate a cartesian product S^n, n>=3, of [a,b,c,d] that excludes > '*a*b*' and '*c*d*a*'. See below for details. I'm afraid that different programs in this thread has understood the asterisk differently: that it matches any single element, or that it matches any sequence of elements. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From florasol at hotmail.com Sun Mar 5 13:13:14 2006 From: florasol at hotmail.com (Francois) Date: 5 Mar 2006 10:13:14 -0800 Subject: Why I chose Python over Ruby References: <1141573450.667103.8930@z34g2000cwc.googlegroups.com> <1141582175.332183.88880@j33g2000cwa.googlegroups.com> Message-ID: <1141582394.745009.260910@v46g2000cwv.googlegroups.com> mensanator at aol.com wrote: > What happened to 3)? > "4)" should have read "3)". I found the typo after I posted. I guess I lack "rigor" myself ! From dd55 at cornell.edu Fri Mar 24 11:22:13 2006 From: dd55 at cornell.edu (Darren Dale) Date: Fri, 24 Mar 2006 11:22:13 -0500 Subject: property docstrings Message-ID: I am trying to work with properties, using python 2.4.2. I can't get the docstrings to work, can someone suggest what I'm doing wrong? I think the following script should print "This is the doc string.", but instead it prints: "float(x) -> floating point number Convert a string or number to a floating point number, if possible." Thanks, Darren class Example(object): _myattr = 0.0 @apply def myattr(): doc = """This is the doc string.""" def fget(self): return self._myattr def fset(self, value): self._myattr = value def fdel(self): del self._myattr return property(**locals()) _foo = 1.0 def foo(): doc = """This is the doc string.""" def fget(self): """This is the doc string.""" return self._foo def fset(self, value): """This is the doc string.""" self._foo = value def fdel(self): """This is the doc string.""" del self._foo return locals() foo = property(**foo()) _bar = 1.0 doc = """This is the doc string.""" def get_bar(self): return self._bar def set_bar(self, value): self._bar = value def del_bar(self): del self._bar bar = property(get_bar, set_bar, del_bar, doc) a=Example() print 'myattr docstring:\n', a.myattr.__doc__ print 'foo docstring:\n', a.foo.__doc__ print 'bar docstring:\n', a.bar.__doc__ From pete at nospam.net Wed Mar 29 21:00:24 2006 From: pete at nospam.net (Pete) Date: Wed, 29 Mar 2006 21:00:24 -0500 Subject: Uninstalling Python References: <122mankrkc6tb11@corp.supernews.com> Message-ID: <122metsra3jpvb0@corp.supernews.com> Ben Finney wrote: > "Pete" writes: > >> I googled "python" and have no interest in it and know nothing about >> it. >> >> Therefore, I would like to uninstall both the versions since I do >> not believe I need them. Would it be okay to uninstall them or >> would you recommend that I keep them even though I will probably >> never use them (ie for the future just in case). > > It should be okay to uninstall *any* software on your system if you > believe you don't want it. > > If you don't have a system that defaults to removing software without > checking if other packages depend on it, I'd hope you have stern words > to say to your operating system vendor and seek out more user-friendly > operating systems. Thanks Ben...I told you in my very first few words who my operating system vendor was (ie non other than "Bill Gates"). I said I was using xpsp2. So do all "windows" xp computer operating systems do what you said (ie, check if other packages depend on something that you are uninstalling). I would certainly hope so, since MS is the world leader with "windows". I am not a pc guru like you are, so when you tell me to seek out more user friendly operator systems, it is over my head. I buy my pc's out of the box with windows installed on them...Pete > > On the other hand, if packaged programs depend on other packages but > don't use the operating system package manager to declare this, those > programs are poorly packaged. > > In short: it's your computer. We hope you'll one day be interested > enough in Python to want to use it some more. For now, if you want to > uninstall it, you should feel free, and demand an explanation from > anything that breaks as a result. From http Mon Mar 13 03:37:25 2006 From: http (Paul Rubin) Date: 13 Mar 2006 00:37:25 -0800 Subject: Is this possible in Python? References: <1142238871.199749.243470@p10g2000cwp.googlegroups.com> Message-ID: <7xu0a2wxiy.fsf@ruckus.brouhaha.com> alainpoint at yahoo.fr writes: > assert magic_function(3+4)=="3+4" > assert magic_function([i for i in range(10)])=="i for i in range(10)]" > > It is not trivial at all and might require some bytecode hacking that i > am unable to do myself BUT you are the experts ;-) Guhhh... you'd want to use the traceback system and reach back into the source code to get and parse the statement that called the magic function, sort of like a debugger does. I don't think messing with the bytecode would help. From gandalf at designaproduct.biz Mon Mar 6 02:57:29 2006 From: gandalf at designaproduct.biz (Laszlo Zsolt Nagy) Date: Mon, 06 Mar 2006 08:57:29 +0100 Subject: Convert dictionary to HTTP POST In-Reply-To: References: <4408084D.4060708@designaproduct.biz> <4408493C.8050901@designaproduct.biz> Message-ID: <440BEB69.1070209@designaproduct.biz> >>The values of some inputs are encoded using html entities. >>How can I decode a string like "Bessy's cat" in "Bessy's cat"? >> >> > >this snippet might help: > > http://effbot.org/zone/re-sub.htm#strip-html > > Thank you, worked like a charm. :-) Laszlo From jstroud at ucla.edu Mon Mar 6 23:25:25 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 06 Mar 2006 20:25:25 -0800 Subject: Checking function calls In-Reply-To: References: Message-ID: Fredrik Tolf wrote: > If I have a variable which points to a function, can I check if certain > argument list matches what the function wants before or when calling it? > > Currently, I'm trying to catch a TypeError when calling the function > (since that is what is raised when trying to call it with an illegal > list), but that has the rather undesirable side effect of also catching > any TypeErrors raised inside the function. Is there a way to avoid that? > > Fredrik Tolf > > Since python is "weakly typed", you will not be able to check what "type" of arguments a function expects. TypeErrors relating to the type of argemtns you pass will be raised inside the function only and not when it is called. I.e. there is no type checking when a function is called, only in its body. Types erros can be raised when calling a function like this: func(*avar) or func(**avar) In the former case, if avar is not a sequence, you will get a TypeError. In the latter case, if avar is not a dictionary, you will get a TypeError. In this latter case, if your dictionary has keys that are not in the parameter list, you will get a TypeError. This would be similar to explicitly specifying a keyword argument that is not in the parameter list (e.g. func(aparam=someval)). TypeError will be raised also if you give an improper number of arguments to the function. So, if you want to know the number of arguments expected, I've found this works: py> def func(a,b,c): ... print a,b,c ... py> func.func_code.co_argcount 3 To check the parameter names, use py> func.func_code.co_names ('a', 'b', 'c') James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From olanglois at quazal.com Sun Mar 19 18:32:10 2006 From: olanglois at quazal.com (Olivier Langlois) Date: Sun, 19 Mar 2006 18:32:10 -0500 Subject: String comparison question Message-ID: <400BDC416E2A0042AA35DF3919BB8A5115E648@mail.mtl.proksim.com> Hi, I would like to make a string comparison that would return true without regards of the number of spaces and new lines chars between the words like 'A B\nC' = 'A\nB C' What would be the easiest way to do it in Python? Thanks, Olivier Langlois http://www.quazal.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From felipe.lessa at gmail.com Thu Mar 23 21:14:15 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Thu, 23 Mar 2006 23:14:15 -0300 Subject: Multiplying all the values in a dictionary In-Reply-To: <44234ee6$1@nntp0.pdx.net> References: <44234ee6$1@nntp0.pdx.net> Message-ID: <1143166455.30386.6.camel@kenshin> Em Qui, 2006-03-23 ?s 17:54 -0800, Scott David Daniels escreveu: > John McMonagle wrote: > > Say I have a dictionary like below: > > > > d = {(100,500):[5,5], (100,501):[6,6], (100,502):[7,7]} > > > > Say I want to multiply all the values of the dictionary by 2: > > for key in d.keys(): > > d[key] = map(lambda x: x*2, d.get(key)) > > Is there a better/faster/cleaner way to achieve this ? > > To update, I'd either go with that or Felipe's list comprehension. > If you just want the value of the result, how about: > > doubled = dict((key, [x * 2 for x in values]) > for key, values in d.iteritems()) And always benchmark: $ python2.4 -mtimeit -s 'd = {(100,500):[5,5], (100,501):[6,6], (100,502):[7,7]}; x = dict(d)' 'for key in d.keys(): x[key] = map(lambda x: x*2, d.get(key))' 100000 loops, best of 3: 8.48 usec per loop $ python2.4 -mtimeit -s 'd = {(100,500):[5,5], (100,501):[6,6], (100,502):[7,7]}; x = dict(d)' 'for key in d: x[key] = [y*2 for y in d[key]]' 100000 loops, best of 3: 3.92 usec per loop You get a large improvement here because: - lambdas are slow compared to direct operations: $ python2.4 -mtimeit -s 'a = lambda x: x*2' 'a(1)' 1000000 loops, best of 3: 0.411 usec per loop $ python2.4 -mtimeit -s 'def a(x): return x*2' 'a(1)' 1000000 loops, best of 3: 0.41 usec per loop $ python2.4 -mtimeit '1*2' 10000000 loops, best of 3: 0.16 usec per loop - d.get(x) is slower than d[x]: $ python2.4 -mtimeit -s 'd = {1:1}' 'd[1]' 10000000 loops, best of 3: 0.172 usec per loop $ python2.4 -mtimeit -s 'd = {1:1}' 'd.get(1)' 1000000 loops, best of 3: 0.363 usec per loop - "for key in d:" is faster than "for key in d.keys():": $ python2.4 -mtimeit -s 'd = {1:1}' 'for k in d: pass' 1000000 loops, best of 3: 0.345 usec per loop $ python2.4 -mtimeit -s 'd = {1:1}' 'for k in d.keys(): pass' 1000000 loops, best of 3: 0.69 usec per loop $ python2.4 -mtimeit -s 'd = {(100,500):[5,5], (100,501):[6,6], (100,502):[7,7]}; x = dict(d)' 'dict((key, [x * 2 for x in values]) for key, values in d.iteritems())' 100000 loops, best of 3: 7.72 usec per loop Here it's slower because it creates another dictionary. But it's a different result, can't be compared directly. HTH, -- Felipe. From sakcee at gmail.com Mon Mar 13 19:08:07 2006 From: sakcee at gmail.com (Sakcee) Date: 13 Mar 2006 16:08:07 -0800 Subject: global namescape of multilevel hierarchy Message-ID: <1142294887.324215.44280@j52g2000cwj.googlegroups.com> Hi I have a script e.g. import package.module ID = "55" package.module.checkID() now in package.module.checkID function, i wnat to know what is the ID defiend in the calling scriipt if I dot globals(), it returns only items in module. is there a way to get the script level namesapce thanks From scott.daniels at acm.org Mon Mar 13 11:29:44 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 13 Mar 2006 08:29:44 -0800 Subject: how exactly do binary files work in python? In-Reply-To: References: <3aGdnZUhQZn-I4nZRVn-jw@speakeasy.net> Message-ID: <44159bda$1@nntp0.pdx.net> Steven D'Aprano wrote: [Generally fine stuff, I am elaborating rather than dis-agreeing.] > On Sun, 12 Mar 2006 22:01:46 -0500, John Salerno wrote: > >> Erik Max Francis wrote: >> >>> You can use the struct module for converting fundamental types to a >>> portable string representation for writing to binary files. >> But if it's a string, why not just use a text file? What does a binary >> file do that a text file doesn't, aside from not converting the end of >> line characters? > > Nothing. It is all bytes under the hood. Modeling a file as "a continuous undifferentiated string of bytes under the hood" is a Unix-ism. There were (and are) other models. > When writing lines to a file, Python does not automatically append the > line marker, so you need to do so yourself. This is, indeed the behavior with "write," but not with "print" A "print" statement ending w/o a comma will tack an end-of-line onto its output. > But some other languages do -- I believe C++ is one of those languages. > So C++ needs to know whether you are writing in text mode so it can > append that end-of-line maker, or binary mode so it doesn't. Actually C++ (and C) convert any ('\12' == '\n' == LF) character to the local file system's "line terminator" character on output to a text-mode file. > Since Python doesn't modify the line you write to the file, it doesn't > care whether you are writing in text or binary mode, it is all the same. Well, actually CPython uses C I/O, so it does convert the '\n' chars just as C does. > Operating systems such as Unix and Linux don't distinguish between binary > and text mode, the results are the same. I'm told that Windows does > distinguish between the two, although I couldn't tell you how they > differ. The way Windows differs from Unix: If the actual file data is built as: f = open('dead_parrot', 'wb') f.write('dead\r\nparrot') f.close() g = open('ex_parrot', 'w') g.write('Dead\nParrot') g.close() ft = open('dead_parrot', 'r') ft.read(6) returns 'dead\np' gt = open('ex_parrot', 'r') gt.read(6) returns 'Dead\nD' fb = open('dead_parrot', 'rb') fb.read(6) returns 'dead\r\n' gb = open('ex_parrot', 'rb') gb.read(6) returns 'Dead\r\n' In case you didn't follow the above too precisely, both files (dead_parrot and ex_parrot) have exactly the same byes as contents. This, by the way, is one of the few places Windows did it "by the standard" and Unix "made up their own standard." The Unix decision was, essentially: "there are too many ways to get in trouble with both CR and LF determining line ending: what do you do for LF-CR pairs, What does a LF by itself mean w/o a CR, .... Let's just treat LF as a single-character line separator." Note how funny this for how you type: you type for a line, but sends a CR ('\r' == '\15' == ASCII 13), which the I/O systems somewhere magically transforms into a LF ('\n' == '\12' == ASCII 10). The C standard (which evolved with Unix) does these translation "for you" (or "to you" depending on your mood) because it was meant to be compatible with _many_ file systems, including those which did not explicitly represent ends-of-lines (text files are such systems are sequences of lines, and there is a maximum length to each line). By the way, before you think such systems are foolish, think about how nice it might sometimes be to get to line 20972 of a file without reading through the entire front of the file. --Scott David Daniels scott.daniels at acm.org From roy at panix.com Thu Mar 2 20:10:34 2006 From: roy at panix.com (Roy Smith) Date: Thu, 02 Mar 2006 20:10:34 -0500 Subject: do design patterns still apply with Python? References: <8SINf.1718$No6.40137@news.tufts.edu> <7x8xrs9xqb.fsf@ruckus.brouhaha.com> Message-ID: In article <7x8xrs9xqb.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Somewhat less often, something is easy in Java and difficult in > Python. Example? From deets at nospam.web.de Tue Mar 7 03:39:32 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 07 Mar 2006 09:39:32 +0100 Subject: SAX/Python : read an xml from the end to the top In-Reply-To: <1141699735.555057.324540@p10g2000cwp.googlegroups.com> References: <1141699735.555057.324540@p10g2000cwp.googlegroups.com> Message-ID: <474v65Fdv6vfU1@uni-berlin.de> kepioo schrieb: > I currently have an xml input file containing lots of data. My objectiv > is to write a script that reports in another xml file only the data I > am interested in. Doing this is really easy using SAX. > > The input file is continuously updated. However, the other xml file > should be updated only on request. > > Everytime we run the script, we track the new elements in the input > file and report them in the output file. > > My idea was to : > _ detect in the output file the last event reported > _ read the input file from the end > _ report all the new events ( since the last time the script was run). > > > > Question : IS it possible to read an XML file and process it from the > end to the beginning, using SAX???? No. And in no other XML-related technology I know of. Generally speaking, I'd say your approach is inherently flawed. XML as a language requires well-formed documents to have exactly one root element. This makes it unsuitable for e.g. logging-files, as these have no explicit "end" - except the implicit last log-entry. So you will always have something like this: --- begin --- --- end --- I don't know _what_ you do, but unless you always write the whole XML-file completely new, you can't possibly write that closing end-tag. So you end up with an malformed xml-document. Or you _do_ write all the file contents new each time - but then you'd be able to reverse the order of elements so that the last came first. But I doubt the latter, as it imposes a great performance-bottleneck with little gain. SAX won't puke on you for your file being malformed, as it only learns about that when it is to late. So - you might use it, as when that happens you are already finished with your actual task. But you will always have to parse it from the beginning, to catch the document header, and there is no fast-forward build into SAX. So - what are your options? - use seperate output files for each entry, that are well-formed in themselves. Beware if you've got plenty of them (few K to M) that some FS might not deal well with that - if you can keep the file open reading all the time (because you are kind of a background process), you can read the contents, create a buffer and search for start-tags in that yourself. Then you can snip out the necessary portions, complete them with a xml-header and feed them separately. - if you can't keep it open, you can simulate that using the seed-function Both the last options are somewhat cumbersome, as you have to do a lot of parsing yourself - the exact purpose one chose XML the first time... From that follows the last advice: - ditch XML. Either totally, or at least as format for the whole file. Instead, use some protocol like this: --- begin --- Chunk-Length: 100 ... ( a 100 byte size xml document) Chunk-Length: 200 ... ( a 200 byte size xml document) ... Then you can easily read through your document, skip unnecessary entries and extract the ones you want. Or, when keeping the file open, know exactly what to read for the next chunk. Diez From jdhunter at ace.bsd.uchicago.edu Wed Mar 29 21:40:15 2006 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 29 Mar 2006 20:40:15 -0600 Subject: Matplotlib: Histogram with bars inside grid lines...how?? References: <1143678532.482987.249610@i39g2000cwa.googlegroups.com> Message-ID: <87y7yshcz4.fsf@peds-pc311.bsd.uchicago.edu> >>>>> "Enigma" == Enigma Curry writes: Enigma> I'm playing around with matplotlib for the first time. I'm Enigma> trying to make a very simple histogram of values 1-6 and Enigma> how many times they occur in a sequence. However, after Enigma> about an hour of searching I cannot make the histogram Enigma> stay within the bounds of the grid lines. Enigma> Here is my example: Enigma> pylab.grid() x_values=[1,1,2,2,2,3,3,3,4,4,4,5,5,6,6,6] Enigma> pylab.hist(x_values,6) pylab.show() Enigma> This produced the following image: Enigma> http://enigmacurry.com/usenet/historgram-bars-not-in-grid-lines.png Enigma> Starting with bar number 2, it creeps into grid 1.. and Enigma> finally with bar number 5 it's almost entirely in grid Enigma> 4.. how do I make the bars stay in their own grid lines? While exactly what you want is something of an enigma to me, I can offer some advice and terminology. The bars of hist make no attempt to stay within the bounds of the grid lines... The bars have as their left most boundary the bins you choose for the histogram. As a first step, I suggest setting these bins explicitly, rather than letting the hist command choose them automatically from pylab import hist, xlim, nx, show x_values= [1,1,2,2,2,3,3,3,4,4,4,5,5,6,6,6] bins = nx.arange(0.5, 7.) hist(x_values, bins) xlim(0,6.5) show() The grid line locations are determined by the xtick locations, which you can set with the xticks command. Good luck! JDH From john_sips_teaz at yahooz.com Wed Mar 1 19:58:50 2006 From: john_sips_teaz at yahooz.com (John M. Gabriele) Date: Wed, 01 Mar 2006 19:58:50 -0500 Subject: Suggestions for documentation generation? In-Reply-To: <1141240014.302680.78850@z34g2000cwc.googlegroups.com> References: <1141240014.302680.78850@z34g2000cwc.googlegroups.com> Message-ID: kpd wrote: > Hello, > > I have written a C++ library that I've then wrapped with Pyrex. > Any suggestions to the best-in-class tool to create documentation for > the libraries? > > I would love to document things in one spot (could be the code) and > generate html and PDF from there. > > Doxygen (www.doxygen.org) looks to be about the best so far. > > Thanks, > I've heard that some folks use pythondoc: http://starship.python.net/crew/danilo/pythondoc/ http://effbot.org/zone/pythondoc.htm There's also HappyDoc http://happydoc.sourceforge.net/ and EpyDoc http://epydoc.sourceforge.net/ . -- (remove zeez if demunging email address) From steve at holdenweb.com Sat Mar 4 03:30:05 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 04 Mar 2006 08:30:05 +0000 Subject: stripping spaces in front of line In-Reply-To: <1141444890.389188.140870@i40g2000cwc.googlegroups.com> References: <1141444890.389188.140870@i40g2000cwc.googlegroups.com> Message-ID: eight02645999 at yahoo.com wrote: > hi > wish to ask a qns on strip > i wish to strip all spaces in front of a line (in text file) > > f = open("textfile","rU") > while (1): > line = f.readline().strip() > if line == '': > break > print line > f.close() > > in "textfile", i added some spaces in and then ran the code, it prints > out the lines without the spaces in front. I double checked "textfile" > and it does contains some lines with spaces in front. > Is it true that "readline().strip()" perform the removing of spaces in > front of a line as well? Is it documented anywhere? > I am using Windows environment. thanks > If you are using Windows then navigate to Start | All Programs | Python 2.4 | Python Manuals. Click the "Index" tab and enter "strip". You will see that there is a strip() function in module string, and that strings have a .strip() method. This is called "Reading the Documentation". Do it more. Your time is no more valuable than that of those who help on this list. Please try to respect it by answering questions as best you can *before* resorting to the list. That way you'll continue to be a welcome visitor. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From joel.hedlund at gmail.com Wed Mar 8 12:00:16 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Wed, 08 Mar 2006 18:00:16 +0100 Subject: Checking function calls In-Reply-To: References: Message-ID: If you have access to the source of the function you want to call (and know what kind of data types it wants in its args) you can raise something else for bad parameters, eg: ---------------------------------------------------------------- class ArgTypeError(TypeError): def __init__(self, arg): self.arg = arg def __str__(self): return "bad type for argument %r" % self.arg def moo(cow): if not isinstance(cow, str): raise ArgTypeError('cow') print "%s says moo!" % cow # this error is not caused by wrong arg type: var = 1 + 's' function = moo for arg in [1, 'rose']: try: function(arg) except ArgTypeError, e: print e ---------------------------------------------------------------- Output: ---------------------------------------------------------------- bad type for argument 'cow' rose says moo! Traceback (most recent call last): File "/merlot1/yohell/eraseme/test.py", line 23, in -toplevel- make_noise('rose') File "/merlot1/yohell/eraseme/test.py", line 13, in moo raise TypeError TypeError ---------------------------------------------------------------- Hope it helps /Joel Hedlund From salvatore.didio at wanadoo.fr Fri Mar 24 15:02:21 2006 From: salvatore.didio at wanadoo.fr (Salvatore) Date: 24 Mar 2006 12:02:21 -0800 Subject: Python types Message-ID: <1143230541.717833.35440@e56g2000cwe.googlegroups.com> Hello, I've read several articles where it's said that Python is weakly typed. I'm a little surprised. All objects seem to have a perfectly defined type Am i wrong? Regards From fuzzyman at gmail.com Mon Mar 20 07:29:42 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 20 Mar 2006 04:29:42 -0800 Subject: compile function and future statements Message-ID: <1142856794.788424.209320@g10g2000cwb.googlegroups.com> Hello all, The following is a copy of a blog entry. It's asking a question about future statements and the built in compile function. I'd appreciate any pointers or comments about possible approaches. `Movable Python `_ supports running both Python scripts and ``.pyc`` bytecode files. It does this by compiling scripts to bytecode, or extracting the code object from bytecode files, and then calling ``exec``. When you call `compile `_ you can pass in an optional ``flags`` argument which tell Python which future statements to compile the code with. I currently don't do this, which means that ``from __future__ import ...`` statements are ignored. For Python 2.4.2 the most significant of these is `division `_. Code which expects integer division to yield floats is just plain broken if this future statement is ignored. I'd like to fix this in the next release of **Movable Python**. First of all, I *assume* that the code objects contained in bytecode files are already compiled with the relevant future statements. This would mean that no further action is necessary. Can anyone confirm if this is correct ? [#]_ For Python scripts there are a couple of possible approaches. The simplest approach would be to use a simple regular expression to find statements that look like ``from __future__ ...``. Unfortunately this could score false positives for comments and docstrings. [#]_ Another alternative would be to parse the code into an abstract syntax tree using the `compiler module `_. I would then have to recognise the import statements in the nodes. I can see that there is an `Import node `_ does anyone have any hints for me with this approach ? I would prefer a solution that works across Python versions 2.2 to 2.5 and beyond. Ominously, the ``compile.compile`` function has unsupported options for passing in ``flags``, so it looks like it doesn't handle it automatically from the parse tree. .. [#] It will actually be easy enough to test. .. [#] Future statements shuld only occur at the toplevel of code, and in fact ought to occur before any other statements (although that was broken in Python 2.4), so it ought to be possible to minimize false positives a bit. From brianomorchoe at yahoo.co.uk Thu Mar 9 14:08:23 2006 From: brianomorchoe at yahoo.co.uk (Brain Murphy) Date: Thu, 9 Mar 2006 19:08:23 +0000 (GMT) Subject: programs Message-ID: <20060309190823.87853.qmail@web25701.mail.ukl.yahoo.com> I still dont know a lot about python, it seems that the only programs that i can write are like dos. I have some songs on my computer and was wondering if i could make it some that when a certain program is ran this song will play. Can i do this? can i make my programs look better looking when run? Brian --------------------------------- Yahoo! Messenger NEW - crystal clear PC to PC calling worldwide with voicemail -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent at kentsjohnson.com Sat Mar 4 07:49:43 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sat, 04 Mar 2006 07:49:43 -0500 Subject: Package organization: where to put 'common' modules? In-Reply-To: <1141419542.750676.176150@z34g2000cwc.googlegroups.com> References: <1141419542.750676.176150@z34g2000cwc.googlegroups.com> Message-ID: <44098830$1_3@newspeer2.tds.net> fortepianissimo wrote: > Say I have the following package organization in a system I'm > developing: > > A > |----B > |----C > |----D > > I have a module, say 'foo', that both package D and B require. What is > the best practice in terms of creating a 'common' package that hosts > 'foo'? I want to be able to > > - Testing modules in D right in D's directory and testing modules in B > in B's directory; > - If possible, minimize the modification to PYTHONPATH or sys.path > while doing the above. What I do is run always from the base directory (violates your first requirement). I make a util package to hold commonly used code. Then B and D both use from util import foo In Python 2.5 you will be able to say (in D, for example) from ..util import foo http://www.python.org/peps/pep-0328.html Kent From steven.bethard at gmail.com Mon Mar 6 11:11:06 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 06 Mar 2006 09:11:06 -0700 Subject: Suggesting the use of StandardError as base of error Exceptions. In-Reply-To: References: Message-ID: Antoon Pardon wrote: > I then took a look at http://docs.python.org/lib/module-exceptions.html > which describes the exception heirarchy as follows: > > Exception > +-- SystemExit > +-- StopIteration > +-- StandardError > | + > | + All kind of error exceptions > | + > +---Warning > + > + All kind of warnings > + > > and came to the conclusion, that it would be better to write my code > as follows: > > for case in all_cases: > try: > treat(case) > except StandardError, ErrInfo: > generate_traceback() You've already been pointed to `PEP 352`_, but just to highlight the salient point, I believe what you want to write is:: try: ... except (KeyboardInterrupt, SystemExit): raise except: ... .. _PEP 352: http://www.python.org/peps/pep-0352.html STeVe From steve at REMOVEMEcyber.com.au Wed Mar 1 02:42:33 2006 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Wed, 01 Mar 2006 18:42:33 +1100 Subject: type = "instance" instead of "dict" References: <1141069989.763239.191140@u72g2000cwu.googlegroups.com> <44035966$1_2@newspeer2.tds.net> <1141072746.685948.251040@j33g2000cwa.googlegroups.com> <440370ce$1_2@newspeer2.tds.net> <1141081177.003471.139820@t39g2000cwt.googlegroups.com> <1141087585.910134.17650@j33g2000cwa.googlegroups.com> <1141172214.657248.256480@t39g2000cwt.googlegroups.com> Message-ID: <44055069.1060904@REMOVEMEcyber.com.au> Cruella DeVille wrote: > This is off topic, but if read the documentation is the answere to > everything why do we need news groups? Because "read the documentation" is NOT the answer to everything. However, it was the answer to your question. > The problem with the > documentation for Python is that I can't find what I'm looking for (and > I didn't even know what I was looking for either). Is that a problem with the docs or with you? Or perhaps a little of both? In any case, now Jonathan Gardner has kindly pointed you at the correct part of the docs, you will be able to read up on it and have a better idea of what to do next time. > And since every > language is well documented... That certainly is not true. > there's no need for these groups. > > I wouldn't ask here without trying to find the solution on my own > first. Good. And now, because people didn't just answer your immediate question, but pointed you at the part of the docs where you can learn things you should know, you may find it easier to solve future problems. -- Steven. From timo.stamm at arcor.de Fri Mar 17 05:22:06 2006 From: timo.stamm at arcor.de (Timo Stamm) Date: Fri, 17 Mar 2006 11:22:06 +0100 Subject: Xah's Edu Corner: The Concepts and Confusions of Pre-fix, In-fix, Post-fix and Fully Functional Notations In-Reply-To: <1142585935.934786.115700@e56g2000cwe.googlegroups.com> References: <1142490052.127055.50130@v46g2000cwv.googlegroups.com> <1142585935.934786.115700@e56g2000cwe.googlegroups.com> Message-ID: <441a8dd7$0$21666$9b4e6d93@newsread2.arcor-online.net> Fuzzyman schrieb: > Roedy Green wrote: >> On 15 Mar 2006 22:20:52 -0800, "Xah Lee" wrote, >> quoted or indirectly quoted someone who said : >> >>> e. For example, the in-fix >>> notation =E2=80=9C(3+(2*5))>7=E2=80=9D is written as =E2=80=9C3 2 5 * + 7 >= >>> =E2=80=9D, where the >> Not that Mr. Lee has ever shown much interest in feedback, but you >> pretty well have stick to vanilla ASCII to get your notation through >> unmangled on newsgroups. > > Hmmm... it displays fine via google groups. Maybe it's the reader which > is 'non-compliant' ? Other charsets than US-ASCII are widely accepted in non-english newsgroups as long as the charset is properly declared. Xah's posting was properly encoded and will display fine in every decent newsreader. Timo From tuvas21 at gmail.com Tue Mar 7 21:43:32 2006 From: tuvas21 at gmail.com (Tuvas) Date: 7 Mar 2006 18:43:32 -0800 Subject: AES encryption In-Reply-To: <1141785420.104468.256060@e56g2000cwe.googlegroups.com> References: <1141742505.544888.253280@e56g2000cwe.googlegroups.com> <1141762684.628567.216910@j52g2000cwj.googlegroups.com> <1141785420.104468.256060@e56g2000cwe.googlegroups.com> Message-ID: <1141785812.820569.237090@j33g2000cwa.googlegroups.com> Ere, I mean testing only symetrical keys, and symetrical messages, nothing more realistic. Sigh. Oh well. It works, and that's the important thing. I don't know if I'll put in support for the larger key sizes, but, I'll leave it be for now. From tchur at optushome.com.au Wed Mar 15 05:16:34 2006 From: tchur at optushome.com.au (Tim Churches) Date: Wed, 15 Mar 2006 21:16:34 +1100 Subject: MS word document generator In-Reply-To: <1142413907.226088.190740@j33g2000cwa.googlegroups.com> References: <1142413907.226088.190740@j33g2000cwa.googlegroups.com> Message-ID: <4417E982.7050707@optushome.com.au> Raja Raman Sundararajan wrote: > Hello guys, > Is there any nice library to generate word documents using Python. > > As of today I am generating a HTML document and then open it with MS > Word. > But the problem is that I am not able to control the pages in the > document and as a result of it the output looks terrible. > > I have been using reportlab's platypus to generate PDF documents. > Its a nice application which allows controlling segments of the pages > programatically. > > I was wondering if there was any library as reportlab to generate word > documents. How about PyRTF to generate Rich Text Format documents which MS-Word will lap up? Thanks to the efforts of Simon Cusack (hi Simon). See http://cheeseshop.python.org/pypi/PyRTF/0.45 Tim C From Duncan.j.Watson at gmail.com Thu Mar 16 15:19:44 2006 From: Duncan.j.Watson at gmail.com (Duncan Watson ) Date: 16 Mar 2006 12:19:44 -0800 Subject: OCR question In-Reply-To: <1142458038.229600.50770@v46g2000cwv.googlegroups.com> References: <1142444151.752495.155250@i40g2000cwc.googlegroups.com> <1142458038.229600.50770@v46g2000cwv.googlegroups.com> Message-ID: <1142540384.647204.204620@p10g2000cwp.googlegroups.com> Excellent suggestion. I found it. I will see what I can do about some edge detection to crop the images so that gocr has an easier time of it. Thanks -Duncan From roy at panix.com Tue Mar 7 19:00:23 2006 From: roy at panix.com (Roy Smith) Date: Tue, 07 Mar 2006 19:00:23 -0500 Subject: Learning different languages References: Message-ID: Rich wrote: > Anyway, my question is: what experience you people have with working > with different languages at the same time? At one point, I was working with Perl, Python, Tcl, and C++ all more or less at the same time. I just kept crib sheets handy, so I could look up syntax whenever I needed to. Which was about every time I needed to write a for loop and didn't have an example handy in the same piece of code to remind me what I was supposed to type. > I'm more thinking about Python, PHP, C++, Perl, Euphoria, which are > languages I'm thinking of learning now. This seems like a reasonable set (I've never heard of Euphoria; I'll need to do some google/wikipedia work tonight on that one :-)). If you're trying to build a good resume, I'd probably add Java and/or C# to the mix. Of course, with a list that long, we're probably talking a year or two of study, unless you plan on doing the most cursory job on each. > How is your experience with handling these paralell?. And what would > you recommend - take one (or perhaps two) at a time, and then continue > with the next? Or is it OK to go ahead with them all, at once? I try to learn a new language per year. Sometimes it's just a quick glance (I spent about a day playing with Forth last year), other times it's a deeper look with a serious project or two (those are generally ones with resume appeal, but not always). In any case, I think one at a time makes the most sense. From mathweijzen at home.nl Tue Mar 28 12:57:08 2006 From: mathweijzen at home.nl (Math) Date: Tue, 28 Mar 2006 19:57:08 +0200 Subject: 1.090516455488E9 / 1000000.000 ??? References: <003d01c65273$fcb2c9d0$0502a8c0@AS4L> <1143561648.11752.8.camel@kenshin> Message-ID: <00a701c65291$0816df10$0502a8c0@AS4L> Thanks this does the job And yes, I really need this accuracy.. Many Thanks ----- Original Message ----- From: "Felipe Almeida Lessa" To: "Fredrik Lundh" Cc: Sent: Tuesday, March 28, 2006 6:00 PM Subject: Re: 1.090516455488E9 / 1000000.000 ??? > Em Ter, 2006-03-28 ?s 16:59 +0200, Fredrik Lundh escreveu: >> and consider using >> >> http://www.python.org/doc/lib/module-decimal.html >> >> instead. > > $ python2.4 > Python 2.4.2 (#2, Nov 20 2005, 17:04:48) > [GCC 4.0.3 20051111 (prerelease) (Debian 4.0.2-4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> from decimal import Decimal >>>> a = Decimal("1.090516455488E15") >>>> a > Decimal("1.090516455488E+15") >>>> b = a / 1000000 >>>> b > Decimal("1090516455.488") >>>> str(b) > '1090516455.488' > > *But*, > > $ python2.4 -mtimeit -s 'from decimal import Decimal; a = > Decimal("1.090516455488E15")' 'a/1000000' > 1000 loops, best of 3: 222 usec per loop > $ python2.4 -mtimeit -s 'a=1.090516455488E15' 'a/1000000' 1000000 loops, > best of 3: 0.234 usec per loop > $ calc 222/0.234 > ~948.71794871794871794872 > > Decimal is almost one thousand times slower. Do you really need this > accuracy? > > HTH, > > -- > Felipe. > > -- > http://mail.python.org/mailman/listinfo/python-list From aleaxit at yahoo.com Fri Mar 3 22:08:44 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 3 Mar 2006 19:08:44 -0800 Subject: How much does Python optimize? References: <440883db$1@nntp0.pdx.net> Message-ID: <1hbn0xi.weokv41pdsuhhN%aleaxit@yahoo.com> Blackbird wrote: ... > >> for i in range(10): > >> ... > > Yup, and if you are tuning a piece of code to the wall, you should > > time it and possibly care. Likely you are not, and the timing makes > > no difference. Someday, range will behave like xrange automagically, ... > Thanks. Yes, this will be a problem for iterations in the order of 10**5 and > upwards only, and those are rare in most applications. So my question was And not crucial when they happen, mostly: helen:~ alex$ python -mtimeit -s'x=10**5' 'for i in range(x): j=i*i' 10 loops, best of 3: 102 msec per loop helen:~ alex$ python -mtimeit -s'x=10**5' 'for i in xrange(x): j=i*i' 10 loops, best of 3: 80.9 msec per loop a 20% difference (for a very lightweight loop body), while measurable, will matter at all only in the hottest of hotspots, the narrowest of bottlenecks. Anyway, do learn about -mtimeit, it's cool indeed for such performance measurements. > more motivated by a general curiosity about the inner workings of the Python > interpreter, and I sort of understand why advanced optimization on an > instruction set like bytecode would be difficult. And in the mean time, I Python deliberately avoids all sorts of optimizations, including obvious ones such as constant hoisting -- the idea being that when you need something hoisted, you can hoist it yourself, and meanwhile by knowing that the compiler is dirt-simple and literal-minded you avoid all kinds of risks connected to optimizer bugs or misunderstandings thereof. Alex From steve at hastings.org Tue Mar 7 20:22:03 2006 From: steve at hastings.org (Steve R. Hastings) Date: Tue, 07 Mar 2006 17:22:03 -0800 Subject: Announcing atomfeed.py, xmlelements.py, and feedutils.py Message-ID: I have written some Python library modules to help with creating Atom syndication feeds. Originally, I had a single module called "PyAtom"; now I have split it up into three modules: xmlelements.py, atomfeed.py, and feedutils.py. You can download these modules from here: http://home.blarg.net/~steveha/atomfeed-0.5.0.tar.gz I wrote these because I wanted a really easy, Pythonic way to create Atom syndication feeds. Here is a bit of sample code from the self-test at the end of atomfeed.py: -- cut here -- cut here -- cut here -- cut here -- cut here -- # Test: generate the "Atom-Powered Robots Run Amok" example # # Note: the original had some of the XML declarations in # a different order than atomfeed puts them. I swapped around # the lines here so they would match the atomfeed order. Other # than that, this is the example from: # # http://www.atomenabled.org/developers/syndication/#sampleFeed s_example = """\ Example Feed urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6 2003-12-13T18:30:02Z John Doe Atom-Powered Robots Run Amok urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a 2003-12-13T18:30:02Z Some text. """ xmldoc, feed = new_xmldoc_feed() feed.title = "Example Feed" feed.id = "urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6" feed.updated = "2003-12-13T18:30:02Z" link = Link("http://example.org/") feed.links.append(link) author = Author("John Doe") feed.authors.append(author) entry = Entry() feed.entries.append(entry) entry.id = "urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a" entry.title = "Atom-Powered Robots Run Amok" entry.updated = "2003-12-13T18:30:02Z" entry.summary = "Some text." link = Link("http://example.org/2003/12/13/atom03") entry.links.append(link) s = str(xmldoc) if s_example != s: failed_tests += 1 print "test case failed:" print "The generated XML doesn't match the example. diff follows:" print diff(s_example, s) -- cut here -- cut here -- cut here -- cut here -- cut here -- I welcome any feedback on these. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From rtilley at vt.edu Thu Mar 2 14:39:25 2006 From: rtilley at vt.edu (rtilley) Date: Thu, 02 Mar 2006 14:39:25 -0500 Subject: white space in expressions and argument lists In-Reply-To: References: Message-ID: John Salerno wrote: > All of it was a joke? You'd have to ask Guido that :) I took it literally when I first read it b/c it made sense to me and I did not notice the date. I don't think it will ever be _required_ of all Python hackers, but I may be wrong. From johnjsal at NOSPAMgmail.com Mon Mar 20 11:01:54 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 20 Mar 2006 16:01:54 GMT Subject: what's the general way of separating classes? In-Reply-To: References: Message-ID: Felipe Almeida Lessa wrote: > And create an program/modules/__init__.py that have something like > > from program.modules.class1 import class1 > from program.modules.class2 import class2 I'm not sure I understand the point of those two lines, if you are going to then do this: > And, in the rest of your program, you can import class1 and class2 by > just issuing > > from program.modules import class1, class2 How does the __init__ file help if you are still individually importing class1 and class2 in each other module of your program? From fredrik at pythonware.com Mon Mar 20 08:25:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Mar 2006 14:25:15 +0100 Subject: String comparison question References: <400BDC416E2A0042AA35DF3919BB8A5115E648@mail.mtl.proksim.com> <1142858790.888174.143470@i40g2000cwc.googlegroups.com> Message-ID: luc.saffre at gmail.com wrote: >> > I would like to make a string comparison that would return true without >> > regards of the number of spaces and new lines chars between the words >> > >> > like 'A B\nC' = 'A\nB C' > > Here is how I do such comparisons: > > if a.strip().split() == b.strip().split() clever solution (I was about to post a split/join solution, but the join is of course meaningless), but the strip() isn't necessary: the default version of split already removes leading and trailing whitespace: >>> " hello world ".split() ['hello', 'world'] >>> " hello world ".split(None) ['hello', 'world'] >>> " hello world ".split(" ") ['', 'hello', 'world', ''] From kent at kentsjohnson.com Sun Mar 5 13:36:15 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sun, 05 Mar 2006 13:36:15 -0500 Subject: Python version of XMLUnit? Message-ID: <440b2ae2$1_2@newspeer2.tds.net> I have found XMLUnit to be very helpful for testing Java and Jython code that generates XML. At its heart XMLUnit is an XML-aware diff - it parses expected and actual XML and pinpoints any differences. It is smart enough to ignore things like attribute order, different quoting and escaping styles, and insignificant whitespace. Now I am working on a CPython project and have a similar need. Is there any comparable tool for Python? Basically I'm looking for a tool to compare XML and show diffs in an intelligible fashion that is usable from Python unit tests (using py.test, if it matters). Thanks, Kent http://xmlunit.sourceforge.net/ From hancock at anansispaceworks.com Thu Mar 16 07:19:55 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 16 Mar 2006 06:19:55 -0600 Subject: Cheese Shop: some history for the new-comers In-Reply-To: References: <44126523$0$1016$afc38c87@news.optusnet.com.au> Message-ID: <20060316061955.4065c03a@samwise.anansi> On Tue, 14 Mar 2006 13:22:09 -0700 Steven Bethard wrote: > A.M. Kuchling wrote: > > On Sun, 12 Mar 2006 10:25:19 +0100, > > Fredrik Lundh wrote: > >> and while you're at it, change "python-dev" to > >"developers" and > "psf" to "foundation" (or use a title > >on that link). > > > > I've changed the PSF link, but am not sure what to do > > about the python-dev link. As others have noted, > > "Developers" is ambiguous about whether it's for people > > who develop in Python or who develop Python itself. > > "Core Development"? (Used on both perl.org and tcl.tk, > > so maybe this is the best option.) "Development Team"? > > +1 on Core Development. It's still ambiguous, but less > so. And I can't think of anything better. ;) Since I just said almost that independently on an earlier thread, I guess that makes me +1 on "Core Development" (or "Core Developers") myself. -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From msoulier at gmail.com Fri Mar 31 13:30:26 2006 From: msoulier at gmail.com (msoulier) Date: 31 Mar 2006 10:30:26 -0800 Subject: exception handling in Tkinter Message-ID: <1143829826.843038.46760@i39g2000cwa.googlegroups.com> In wxPython I install a top-level exception handler to intercept exceptions and display them in the GUI. With Tkinter, I'm trying to do the same. in __init__ sys.excepthook = self.ExceptionHandler def ExceptionHandler(self, type, value, tb): tblist = traceback.format_tb(tb) for line in tblist: text += line self.errorDialog(text) But it's not being called on exceptions. Any ideas? Thanks, Mike From adam.deprince at gmail.com Thu Mar 23 22:04:07 2006 From: adam.deprince at gmail.com (adam.deprince at gmail.com) Date: 23 Mar 2006 19:04:07 -0800 Subject: Getting a loop to activate a loop above it References: <1143061653.100159.127550@u72g2000cwu.googlegroups.com> Message-ID: <1143169447.332122.105970@j33g2000cwa.googlegroups.com> This is how python is supposed to work. I'm sure not what languages you have used ... it seems that you are expecting some sort rule based system like make, or prolog. Grab a cup of joe, pull up a chair and let me help you out here. Python is an imperative language, you can envision the presence of a "program counter" that starts at the first line. If my program says: print 1 print 2 print 3 Python will print: 1 2 3 because the program counter (forgive me for calling it that) was at the "print 1" ... its sequential top to bottom. Now the while command means: while Spin around madly and execute all of the commands in this indented section and if you got here then it means that your expression wasn't true anymore . So, what happened is you: >>> x = 1 Obviously the variable x has the value 1. >>> while x == 1: >>> ... Okay, we enter the while loop ... print 'Hello', You tried telling it 2. Well, it didn't jump to 2 because that was a rule, it jumped because after your input x=2, not 1. The while state's expression failed and the control, or your program counter, jumped outside of your first block. When it wandered to your second loop it discoverd "x==2" is a true statement by luck. Had you entered 3, you would never, ever have been told hello again ... if the intiial condition of a while statement is false, then you never enter the while. Now, after leaving your second loop, it isn't going back. The program counter is behind that all, and will never ever go back to the top unless you tell it. And how do you tell it? while True: Things I want done over and over again forever or until I stumble across a break statement I'm going to assume that you are not suffering from the effects of chronic makefile over exposure and send you here http://docs.python.org/tut/tut.html Jordan Greenberg seems to have written what you were trying to do ... but unless you give us a script of what you wanted to see in response to what you entered, then we can't know. Jordan Greenberg's example is right, but I would have written it differently. I would have said: x=1 while x !=3: if x==1: print "Hello" elif x==2: print "Hello again" x = input( 'what is x now?: ') Just a nit pick that is unrelated. One of the principals of clean programming (look up refactoring) is to write things once. When you have two program paths that merge, common code at the end of each should be moved past the merge so its only written once. In your example, or John's, what if you decided that you wanted your input statement to ask the question in Italian? input( "Che cosa ora e' x?: ") Its better to change in one place than to. Lastly, I have a small rant about the input function. Don't use input. Please please promise me the following. Never, never, use the input command in any user facing software. I used to be tempted, well, not since I was 13, especially as BASIC was my first language (TI-994/A home computer) to write programs like this: print "Your first parameter" a = input ... print "Your sencond parameter" b = input If you are at the command line, use getopts, curses, use the plain python shell and call the function myfunc( a=, b= ). Don't write a program that uses input to collect user input on the command line and hand it to somebody at work to use. Especially if the program gives them the appearnce of being in a protected environment. If you were to enter this (please don't, its destructive, it will erase your files and kill your pets): map( __import__('os').unlink, __import__('glob').glob('*') ) instead of 1 or 2, all of your files in your current directory would be deleted instead of printing "hello again." And your dog will run away. Anything that connected the ability to evaluate code is dangerous. This is why we give user mice instead of soldering irons. Please. Don't use input. Think about the children. From brandon.mcginty at gmail.com Sun Mar 19 19:16:44 2006 From: brandon.mcginty at gmail.com (brandon.mcginty at gmail.com) Date: Sun, 19 Mar 2006 17:16:44 -0700 Subject: Keeping a function from taking to long--threads? Message-ID: <000001c64bb3$93259220$6700a8c0@D1FWTS61> Hi All, Just wondering if anyone knows of a way to keep a function, E.g. socket.gethostbyaddr("12.34.56.78"), >From taking to long-if it's run for more than 1 second, the function gethostbyaddr will be terminated? I was thinking about using threads, but I can't seem to get the hang of them. I've tried to have the script break if the clock time is greater than 1 second, but python won't respond to anything until the function finishes, not surprisingly. Sorry if there is a very obvious answer to this... The below program is to do a search on our wireless network at work, so that we can find any rogue computers that aren't supposed to be there. Code: #code starts import socket import sys changingip=[] ip=sys.argv[1] ip=ip.split(".") for i in range(0,254): ipaddr=ip[0]+"."+ip[1]+"."+ip[2]+"."+str(i) try: #the next line is my issue; I need to make sure it doesn't go over 1 second while running print socket.gethostbyaddr(ipaddr) #the next block is to ensure that if the ip I am checking doesn't exist on the network, the script will move along to the next ip except: pass #end of script #I know the code isn't pretty, but except for the timeing issues, it works great. Any help is greatly appreciated. THX, Brandon McGinty -- No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.1.385 / Virus Database: 268.2.5/284 - Release Date: 3/17/2006 From bearophileHUGS at lycos.com Thu Mar 9 10:19:56 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 9 Mar 2006 07:19:56 -0800 Subject: First script, please comment and advise References: Message-ID: <1141917596.011498.311500@p10g2000cwp.googlegroups.com> My version is similar to Just one: from random import shuffle def scramble_text(text): """Return the words in input text string scrambled except for the first and last letter.""" def scramble_word(word): if len(word) < 4: return word core = list(word[1:-1]) shuffle(core) return word[0] + "".join(core) + word[-1] return " ".join(map(scramble_word, text.split())) print scramble_text(scramble_text.__doc__) From duncan.booth at invalid.invalid Sun Mar 5 10:25:04 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Mar 2006 15:25:04 GMT Subject: Inline assignments References: Message-ID: Fredrik Tolf wrote: > However, since I can't do that in Python, I ended up using an extra > local variable instead, like this: > > f = getattr(self, "cmd_" + name) > f2 = getattr(self, "cmdv_" + name) > if callable(f): > # Do something with f > elif callable(f2): > # Do something with f2 If 'do something' is the same thing: for prefix in ('cmd_', 'cmdv_'): f = getattr(self, prefix+name) if callable(f): # do something with f break If 'do something' is different each time, put each block into a method: def do_cmd(self, f): ... def do_cmdv(self, f): ... ... for prefix, action in (('cmd_', self.do_cmd), ('cmdv_', self.do_cmdv)): f = getattr(self, prefix+name) if callable(f): action(f) break > > Another common problem for me are while loops. I would often like to do > this: > while (pos = somestring.find("/")) != -1: > part = somestring[:pos] > somestring = somestring[pos + 1:] > # Handle part for part in somestring.split("/")[:-1]: # handle part Are you sure you didn't want to process the last part of the string as well? I would have thought that to be more common, and rather harder to write using your original structure. > > Which is quite ugly. This might have been a bad example, since > somestring.split() could be used instead, but it's still valid for other > situations. > Not really. Your original loop refactors quite nicely by calling a method or function which returns a sequence of results. The same pattern in will always be refactorable in the same way. If the appropriate 'split' function doesn't already exist then you can write it. A very common way to rewrite this sort of loop these days is to write a generator. It is usually beneficial to factor out the complex part of the loop logic in this way as then you only have to write it once no matter how many loops you have with the same structure. From http Tue Mar 21 00:58:45 2006 From: http (Paul Rubin) Date: 20 Mar 2006 21:58:45 -0800 Subject: Pycrypto - active ?? References: <1142804398.710230.117640@j33g2000cwa.googlegroups.com> <1142807299.141313.306980@i40g2000cwc.googlegroups.com> <1142841321.980154.320340@u72g2000cwu.googlegroups.com> <7xslpdl7yg.fsf@ruckus.brouhaha.com> <1142856119.461122.293150@i40g2000cwc.googlegroups.com> <1142861008.662593.172900@t31g2000cwb.googlegroups.com> <1hchm5b.1vgq264sk3olaN%aleaxit@yahoo.com> <1142919313.863978.133190@i40g2000cwc.googlegroups.com> Message-ID: <7xbqw0bap6.fsf@ruckus.brouhaha.com> "Frank Millman" writes: > I have revisited what I did a week ago, and I now recall that I *did* > successfully install GMPY, but it made no difference to the speed of > TLSLite. I could try to dig deeper by examining the source code of > TLSLite, but it is low priority for me at present. The fact that I got > SSL/TLS working is a big win, and the speed test was a theoretical > exercise. For practical purposes, it is fast enough. TLSLite's main causes of slowness are: 1) time needed compiling and loading all the modules, especially the first time you run it in a new installation; 2) very slow speed of the symmetric ciphers implemented in Python. You need m2crypto, cryptlib, or pycrypto to speed these symmetric operations up. GMPY speeds up the public key operations, which otherwise use Python's native long int arithmetic. But the public key operation is done only at the start of the session, and Python's arithmetic (though slower than GMPY) is implemented in C and is not all that bad. On a modern machine, the difference from GMPY is maybe a few tens of milliseconds at the start of the TLS session, and none at all (the public key phase is finished) once the session is established. TLSLite is so far not really a complete SSL implementation by itself. It doesn't know how to properly check the signatures on certificate chains. It has to use an external module like m2crypto for that. From scott.daniels at acm.org Mon Mar 20 12:36:59 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 20 Mar 2006 09:36:59 -0800 Subject: New-style Python icons In-Reply-To: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> Message-ID: <441ee5e7$1@nntp0.pdx.net> and-google at doxdesk.com wrote: > > You can also see a preview here: > http://www.doxdesk.com/img/software/py/icons.png Maybe you could change the ink color to better distinguish the pycon and pyc icons. -- -Scott David Daniels scott.daniels at acm.org From tjreedy at udel.edu Sun Mar 5 13:46:02 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 5 Mar 2006 13:46:02 -0500 Subject: is there such a built-in funciton, similar to filter References: <1141554823.501805.224790@e56g2000cwe.googlegroups.com> Message-ID: "Michael Hoffman" wrote in message news:dueg7q$o4p$1 at gemini.csx.cam.ac.uk... > wcc wrote: > >> Beginner learning Python here. I know filter(lambda x: x > 3, [1, 2, >> 5, -3, 4, 8]) will give me a list [5, 4, 8]. What if I only need to >> find the first item in the list that returns Ture when applying the >> filter function. In this case, I only want to get the 5, and its index You have made two important changes to the function return value. Filter returns a list of items. You want an item and index. What if there is no first item? >> 2. Is there a built-in function, or function from a module for that? >> I think it is not hard to write a function for this. But knowing >> Python is "battery included", I thought I'd like to ask. A 'battery' is something like the email, html, xml modules that assist major application areas. Not every easily written 3-line function ;-) > You can use a generator expression like this: > > >>> items = [1, 2, 5, -3, 4, 8] > >>> ((index, item) for index, item in enumerate(items) if item > > >>> 3).next() > (2, 5) >>> items = [0,1,2,3] >>> ((index, item) for index, item in enumerate(items) if item > 3).next() Traceback (most recent call last): File "", line 1, in -toplevel- ((index, item) for index, item in enumerate(items) if item > 3).next() StopIteration I believe ifilter from the itertools module will act the same. Terry Jan Reedy From sathyaish at gmail.com Tue Mar 28 09:08:51 2006 From: sathyaish at gmail.com (Sathyaish) Date: 28 Mar 2006 06:08:51 -0800 Subject: in-place string reversal Message-ID: <1143554931.104392.187480@i39g2000cwa.googlegroups.com> How would you reverse a string "in place" in python? I am seeing that there are a lot of operations around higher level data structures and less emphasis on primitive data. I am a little lost and can't find my way through seeing a rev() or a reverse() or a strRev() function around a string object. I could traverse from end-to-beginning by using extra memory: strText = "foo" strTemp = "" for chr in strText: strTemp = chr + strTemp but how would I do it in place? Forget it! I got the answer to my own question. Strings are immutable, *even* in python. Why not! The python compiler is written in C, right? It is amazing how just writing down your problem can give you a solution. PS: Or, if my assumption that strings are immutable and an in-place reversal is possible, is wrong, please correct me. From bronger at physik.rwth-aachen.de Wed Mar 8 17:31:56 2006 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 08 Mar 2006 23:31:56 +0100 Subject: Extending embedded Python: Adding single methods References: <87slpt0wrt.fsf@wilson.homeunix.com> Message-ID: <87veuobmar.fsf@wilson.homeunix.com> Hall?chen! Thomas Heller writes: > Torsten Bronger wrote: > >> [...] However, is there a way to avoid this dummy "pp3" module >> and add the C++ functions directy to the main namespace in the >> Python script? > > Yes. You can import __builtin__, and add methods to it. This is > a snippet from the bdist_wininst code, which embeds Python: > > http://svn.python.org/view/python/trunk/PC/bdist_wininst/install.c?rev=38414&view=markup > > PyMethodDef meth[] = { > {"create_shortcut", CreateShortcut, METH_VARARGS, NULL}, > {"get_special_folder_path", GetSpecialFolderPath, METH_VARARGS, NULL}, > {"get_root_hkey", (PyCFunction)GetRootHKey, METH_NOARGS, NULL}, > {"file_created", FileCreated, METH_VARARGS, NULL}, > {"directory_created", DirectoryCreated, METH_VARARGS, NULL}, > {"message_box", PyMessageBox, METH_VARARGS, NULL}, > }; > > > ... > mod = PyImport_ImportModule("__builtin__"); > if (mod) { > int i; > for (i = 0; i < DIM(meth); ++i) { > PyObject_SetAttrString(mod, meth[i].ml_name, > PyCFunction_New(&meth[i], NULL)); > } > } > ... Thank you, it works well. Just one more question: Why isn't "mod" Py_DECREFed again? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus ICQ 264-296-646 From johnjsal at NOSPAMgmail.com Tue Mar 21 16:07:08 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 21 Mar 2006 21:07:08 GMT Subject: - Python Newcomer Starting with Coding In-Reply-To: <1142970976.052830.325220@j33g2000cwa.googlegroups.com> References: <441fde5d$0$29689$636a55ce@news.free.fr> <6ig0221dcrdfhimmvornfs94qmodi7hqsv@4ax.com> <1142970976.052830.325220@j33g2000cwa.googlegroups.com> Message-ID: <0WZTf.1809$No6.41011@news.tufts.edu> Chris Lasher wrote: > And there's always Mark Pilgrim's very good and very free "Dive Into > Python". > http://www.diveintopython.org/ > Reading that now...definitely not for a newbie. From caleb.hattingh at gmail.com Fri Mar 24 17:11:01 2006 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 24 Mar 2006 14:11:01 -0800 Subject: New development windows, IronPython or PythonWin In-Reply-To: <1143200704.159705.60350@j33g2000cwa.googlegroups.com> References: <1143135013.513865.103820@u72g2000cwu.googlegroups.com> <1143166004.664604.207250@j33g2000cwa.googlegroups.com> <87slp8pfnv.fsf@ieee.org> <1143200704.159705.60350@j33g2000cwa.googlegroups.com> Message-ID: <1143238261.882986.162960@i39g2000cwa.googlegroups.com> Hi Dan Pythonwin just adds support for specifically MS Windows features, most prominently COM; writing Excel scripts in python is so cool. The standard python distribution for windows runs perfectly on windows. I'm not sure whether this was clear to you or not. Also, Thomas ctypes and comtypes (by Thomas(?) Heller) also allow COM integration, though I don't think it is as complete as the pythonwin support. Also, I think IronPython is also supported by only one guy - Jim Hugunin. The fact that IronPython development is effectively being sponsored by Microsoft doesn't fill me with great expectations either, although it would be a good thing if they really supported it well. rgds Caleb From bentton at gmail.com Fri Mar 10 11:36:57 2006 From: bentton at gmail.com (Benny) Date: Fri, 10 Mar 2006 17:36:57 +0100 Subject: Python Evangelism In-Reply-To: <1142005777.058808.198630@e56g2000cwe.googlegroups.com> References: <1142005777.058808.198630@e56g2000cwe.googlegroups.com> Message-ID: <1213apcnisvatb9@corp.supernews.com> Paul Boddie wrote: > Bizarre names may be cute (to some people) but they don't lend > themselves to guessing or searching. Consequently, people who want > answers yesterday aren't likely to be amused to eventually discover > that the name of the resource they've been looking for is some opaque, > three-levels-of-indirection-via-irony, in-crowd joke. And even acronyms > like CPAN are better than wacky names, anyway. To emphasize the point as a newbie: I know what CPAN is. I would go to the Vaults of Parnassus for Python stuff. But Cheese Shop? -- Rod From jussij at zeusedit.com Thu Mar 2 22:59:31 2006 From: jussij at zeusedit.com (jussij at zeusedit.com) Date: 2 Mar 2006 19:59:31 -0800 Subject: how do you move to a new line in your text editor? References: <%ZGNf.1711$No6.40016@news.tufts.edu> Message-ID: <1141358371.007444.240170@i40g2000cwc.googlegroups.com> > One thing I like to do is use tabs for my indentation, because > this makes it easy to outdent when I need to start a new line > in column 1. I can press backspace once and move 4 spaces to > the left. Zeus has a Smart Backspace feature (configurable on or off) where by it will try to line up the current line with the lines of code above on any backspace key press. This means that in the case you describe a backspace will always move back 4 spaces whether the white space is made up of tabs or spaces. > But I read in the PEP that spaces are recommended over tabs. If > this is the case, it would involve pressing backspace 4 times (or > 8, etc.) to get back to column 1. It only takes one key press if you are using Zeus ;) Jussi Jumppanen Author: Zeus for Windows Zeus for Windows IDE http://www.zeusedit.com From caleb.hattingh at gmail.com Wed Mar 29 15:08:36 2006 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 29 Mar 2006 12:08:36 -0800 Subject: operation complexities of lists and dictionaries In-Reply-To: <1143653885.205290.93550@u72g2000cwu.googlegroups.com> References: <1143653885.205290.93550@u72g2000cwu.googlegroups.com> Message-ID: <1143662916.081705.67150@t31g2000cwb.googlegroups.com> Hi Use the "timeit" module, like so: >>> from timeit import Timer >>> t = Timer('[i for i in range(10000)]') # The string is code to execute (for timing) >>> print t.timeit(100) # execute it 100 times and print the result 0.222389936447 I would appreciate it if you could present your results in this thread. I have also been wondering about timings for simple operations. Thanks Caleb From tdwdotnet at gmail.com Thu Mar 23 11:14:10 2006 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Thu, 23 Mar 2006 16:14:10 +0000 Subject: raw_input (was "no subject") Message-ID: <9afea2ac0603230814m58af3f2bn@mail.gmail.com> On 23/03/06, cm012b5105 wrote: > > Hi there i am hoping some one could help me out with a small problem i am > in the process of learning python. I am trying to write an interactive > programme, > This is a short example. > if s = raw_input ("hello what's your name? ") > if s=='carmel': > print "Ahh the boss's wife" > > What i would like to know is what if she dont write carmel she rights say > carm short of me writing if s=='carm': on a new line is there a shorter > way of doing this so i can cover all angles on how she might write her > name. > Thanks nige > >>> s = raw_input ("hello what's your name? ") Traceback ( File "", line 1 if s = raw_input ("hello what's your name? ") ^ SyntaxError: invalid syntax >>> s = raw_input ("hello what's your name? ") # carmel >>> if s=='carmel': ... print "Ahh the boss's wife" ... Ahh the boss's wife >>> HTH :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From doug.bromley at gmail.com Thu Mar 9 04:53:01 2006 From: doug.bromley at gmail.com (Doug Bromley) Date: Thu, 9 Mar 2006 09:53:01 +0000 Subject: New python.org website In-Reply-To: <1141856429.439633.221750@p10g2000cwp.googlegroups.com> References: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> <1141803728.187013.195770@v46g2000cwv.googlegroups.com> <1141832835.420083.154930@u72g2000cwu.googlegroups.com> <1141856429.439633.221750@p10g2000cwp.googlegroups.com> Message-ID: <288425520603090153s711ca3c9h216ab9c84f93d8a@mail.gmail.com> I much prefer the look and feel of the potential Ruby websites being developed at the moment. The Python site is very corporate and academic which could put many early adopters off. I'm sure you've all heard accusations that Python doesn't have the marketing drive of Ruby. Perhaps this is an example where we could do with taking a leaf out of Ruby's book? (http://redhanded.hobix.com/redesign2005/) ----- Doug Bromley blog.straw-dogs.co.uk On 8 Mar 2006 14:20:29 -0800, Kay Schluehr wrote: > > > Michael Tobis wrote: > > > No one > > > of the complainers and negativists do claim that they could do it much > > > better. > > > > Indeed, I do not have to be able to write a particular program to > > notice it has bugs. > > > > On the other hand, (since I think the design, while not brilliant, is > > good) fixing the logo is something that can be achieved without too > > much fuss. > > > > > But I think at times it might be usefull to consult > > > professional aid. > > > > In the case of the logo design, I am not sure I agree. > > > > I think the twisted logo > > > > http://saph.twistedmatrix.com/blog/archives/twisted.png > > > > and the PyCon logo > > > > http://mirrors.ccs.neu.edu/Python/pub/old-www/pics/pycon-logo.gif > > > > were probably not designed by professional designers but rather by > > people who appreciate Python, and yet do have more appeal to the > > community and the outside world alike. If we are going to use a snake > > motif, we should use snakes that look like snakes. > > Maybe its time for me to abandone this discussion. If you and others > feel quite well represented by a pasty and wordy snake than go for it. > I do neither feel embraced nor bitten by it. And I don't just mean the > logo. We can do an awfull lot of comparisons with pages that failed but > this doesn't bring forth anything. > > This evening we talked at the Hofbraeuhaus at Munich about Michelangelo > whose sixtine chapel images where once overpainted because his figures > appeared naked "as god created them". But maybe he was wrong and his > customer, the pope, was right and they were actually born with a leaf > covered their pubic hairs? The pope had to take responsibility and had > to appease possible and real critics. We can assume he was far from > being an idiot but a serious man - a politician. As a serious person > myself I'm always a little splitted between Michelangelo and the pope. > My own idealism expects Michelangelo doing such outstanding things that > it is beyond anything. Nothing could be better than having the uptights > as the most severe enemies. What a fun! But as it seems my political > party is guided by ordinary indifferent humans as well and Michelangelo > may be as much attracted by it as I am by e.g. the german social > democratic party? So I should track back and rethink "the professional > aid" which might be not what I'm really looking for. Guido feels a deep > joy about the resonance between Python and an programmer and artist - > Juergen Scheible - who likes the language, feels inspired by it and > creates a little artwork for Nokia 60s. So there is some inversion in > the right direction. Suddenly Python appears a bit distorted within > another context and it becomes sexy again. Should we talk about Apple > next ... ? > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From spambucket at example.com Mon Mar 27 04:13:28 2006 From: spambucket at example.com (Simon) Date: Mon, 27 Mar 2006 10:13:28 +0100 Subject: HIRING: PHP Developer References: <1143313877.802242.206050@i40g2000cwc.googlegroups.com> <1143449570.820018.167090@t31g2000cwb.googlegroups.com> Message-ID: <48pohkFl7prdU1@individual.net> >I apologize. Google groups has restricted our contact email. To reach > us, please send your quote to hiringdivision @ gmail.com. > > Thank you. Apologize to whom? Who/What are you replying to? Please note that we don't all use Google groups format your replies properly. Simon -- http://urlkick.com/ Free URL redirection service. Turns a long URL into a much shorter one. From 007 at corenetworks.com.au Tue Mar 28 02:19:19 2006 From: 007 at corenetworks.com.au (Matt) Date: Tue, 28 Mar 2006 18:19:19 +1100 Subject: embed notepad into a frame widget Message-ID: <122hotpiojvre6b@corp.supernews.com> all, trying to load an application (notepad for instance) and have it sit inside a Python application window. When the main window maximises or minimises, the (notepad) app follows. I am pretty sure I need to use a frame widget under tkinter (win32) but not exactly sure how to do it. I can make the frame but not embed notepad. do I use something like this? from Tkinter import * master = Tk() frame = Frame(width=768, height=576, bg="", colormap="new") frame.pack() video.attach_window(frame.window_id()) <--- not sure!! mainloop() Thanks -Matt From fuzzyman at gmail.com Fri Mar 17 04:39:07 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 17 Mar 2006 01:39:07 -0800 Subject: split() can help to read UTF-16 encoded file without codecs support, why? In-Reply-To: References: Message-ID: <1142588347.174723.180910@z34g2000cwc.googlegroups.com> Zhongjian Lu wrote: > Hi Guys, > > I was processing a UTF-16 coded file with BOM and was not aware of the > codecs package at first. I wrote the following code: > ===== Code 1============================ > for i in open("d:\python24\lzjtest.xml", 'r').readlines(): > i = i.decode("utf-16") > print i > ======================================= > Output was: > Traceback (most recent call last): > File "D:\Python24\testutf-16.py", line 4, in -toplevel- > i = i.decode("utf-16") > File "D:\Python24\lib\encodings\utf_16.py", line 16, in decode > return codecs.utf_16_decode(input, errors, True) > UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position > 84: truncated data > UTF16 is a 'two-byte encoding'. This means that '\r\n' is represented using : '\r\x00\n\x00' When you use readlines to split this up it splits on byte boundaries. This probably returns something like : '\r', '\x00\n', '\x00' You can see how the last bit is 'truncated' (single byte only) because the data has been split on bytes instead of characters. > I searched google and found an article on the similar problem saying to use > split(). I had not quite caught the meaning of the article and recode as: > ==== Code 2============================== > for i in open("d:\python24\lzjtest.xml", 'r').read().split('\r\n'): > i = i.decode("utf-16") > print i > ======================================= > Then it worked (echo the file). > You will probably find that '\r\n' never occurs in the byte-string, so this does it *all* in one line, but the decode succeeds. HTH All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Later I get to know codecs and write the following code: > > ==== Code 3 ============================= > import codecs > for i in codecs.open("d:\python24\lzjtesttvs2.xml", 'r', 'utf-16').readlines(): > print i > ======================================= > It worked and echo the file. > > I am wondering what is the problem with the first code and why the bug > is fixed in > the second. > > Thanks in advance. > > -Zhongjian From aleaxit at yahoo.com Thu Mar 16 23:34:48 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 16 Mar 2006 20:34:48 -0800 Subject: Threads modify "global" variable -- asking for trouble? References: <1142567916.313302.109920@i39g2000cwa.googlegroups.com> <1142568360.823100.3460@i40g2000cwc.googlegroups.com> Message-ID: <1hcb7ky.1urm3y1r27810N%aleaxit@yahoo.com> J Rice wrote: > My apologizes, I missed the newish FAQ entry on this. The addrbl() > method looks like this: > > def addRBL(self, testname, result, info=""): > self.testresultsRBL[testname] = result, info > > So according to the FAQ, D[x] = y, where D is a dictionary, is atomic > and therefore thread-safe. Right? In the current implementation specifically, for CPython exclusively, if the hashing of testname is itself somehow 'atomic', and so is the access to attribute testresultsRBL of object self, I do believe you might luck out and end up "atomic" (by accident of implementation, only) if everything's just right. Of course, any tiny change (any different implementation of Python, any type that's not a pure primitive, any future version of Python, etc, etc) could break this extremely fragile set of circumstances -- Python as a language makes no guarantees of atomicity for anything except the synchronization primitives (of which Queue is the most powerful). There was a rather heated exchange on the subject quite recently on this group. Just put a lock acquire/release around this assignment (and any _use_ of the same dictionary) and you should be vastly safer, IMNSHO. Alex From g.brandl-nospam at gmx.net Sat Mar 18 12:56:54 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sat, 18 Mar 2006 18:56:54 +0100 Subject: __dict__ strangeness In-Reply-To: <1hce2nh.hnzrzu1qt4yv2N%aleaxit@yahoo.com> References: <482lr6Fhs1jvU1@individual.net> <1hce2nh.hnzrzu1qt4yv2N%aleaxit@yahoo.com> Message-ID: <482vv6FhvsivU1@individual.net> [moving to python-dev] Alex Martelli wrote: > Georg Brandl wrote: > >> can someone please tell me that this is correct and why: > > IMHO, it is not correct: it is a Python bug (and it would be nice to fix > it in 2.5). Fine. Credits go to Michal Kwiatkowski for discovering that in bug #1448042 which I closed out of ignorance ;) >> >>> class C(object): >> ... pass >> ... >> >>> c = C() >> >>> c.a = 1 >> >>> c.__dict__ >> {'a': 1} >> >>> c.__dict__ = {} >> >>> c.a >> Traceback (most recent call last): >> File "", line 1, in ? >> AttributeError: 'C' object has no attribute 'a' > > So far so good, I think we agree;-). Yes. >> >>> class D(object): >> ... __dict__ = {} >> ... >> >>> d = D() >> >>> d.a = 1 >> >>> d.__dict__ >> {} >> >>> d.__dict__ = {} >> >>> d.a >> 1 > > Yep, that's the bug, fully reproducible in 2.3 and 2.4. FWIW, mucking > around with gc.getreferrers (with a more uniquely identifiable value for > d.a;-) shows a dictionary "somewhere" with keys 'a' and '__dict__'... Georg From bdesth.quelquechose at free.quelquepart.fr Mon Mar 6 18:14:58 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 07 Mar 2006 00:14:58 +0100 Subject: Fetch info from website and write to txt file. In-Reply-To: <1141668524.914676.252460@z34g2000cwc.googlegroups.com> References: <1141668524.914676.252460@z34g2000cwc.googlegroups.com> Message-ID: <440c97c0$0$27078$626a54ce@news.free.fr> Pitmairen a ?crit : > I want to make a program that get info from a website and prints it out > in a txt file. > > I made this: > > import urllib > f = urllib.urlopen("http://www.imdb.com/title/tt0407304/") > s = f.read() > k = open("test.txt","w") > k.write(s) > k.close() > f.close() > > That saves all the html code into the test.txt file. But if i for > example only want the genre, plot outline and Cast overview to be > written to the txt file. How can i do that? > Seems like you want BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/ > And another problem i have: > > If the txt file i want the information to be saved in already have some > text saved in it. How can i save the info from the website between the > text that was there before? > > for example: > > blablablablablablablabla > blablablablablablablabla > blablablablablablablabla > (inset info from website here) > blablablablablablablabla > blablablablablablablabla > blablablablablablablabla > You need to be able to identify the place where you want to insert your data. Then it's a matter of reading the original file, creating a temp file, writing lines before insertion point, writing data to insert, writing remaing lines, closing all files, replacing original file by the temp file. From bencvt at gmail.com Mon Mar 20 19:30:57 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 20 Mar 2006 16:30:57 -0800 Subject: Function params with **? what do these mean? References: <1142887602.977736.300990@u72g2000cwu.googlegroups.com> Message-ID: <1142901057.157980.188200@t31g2000cwb.googlegroups.com> Dave Hansen wrote: > On 20 Mar 2006 15:45:36 -0800 in comp.lang.python, > aahz at pythoncraft.com (Aahz) wrote: > >Personally, I think it's a Good Idea to stick with the semi-standard > >names of *args and **kwargs to make searching easier... > > Agreed (though "kwargs" kinda makes my skin crawl). Coincidentally, "kwargs" is the sound my cat makes when coughing up a hairball. Fortunately, **kw is also semi-standard. --Ben From bdesth.quelquechose at free.quelquepart.fr Fri Mar 24 17:38:04 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 24 Mar 2006 23:38:04 +0100 Subject: Help: Creating condensed expressions In-Reply-To: References: Message-ID: <44244798$0$18927$626a54ce@news.free.fr> David Hirschfield a ?crit : > Here's the problem: Given a list of item names like: > > apple1 > apple2 > apple3_SD > formA > formB > formC > kla_MM > kla_MB > kca_MM > > which is a subset of a much larger list of items, > is there an efficient algorithm to create condensed forms that match > those items, and only those items? Such as: > > apple[12] > apple3_SD > form[ABC] > kla_M[MB] > kca_MM > The condensed expression syntax only has [...] and * as operators. [...] > matches a set of individual characters, * matches any string. > I'd be satisfied with a solution that only uses the [...] syntax, since > I don't think it's possible to use * without potentially matching items > not explicitly in the given list. > > I'm not sure what this condensed expression syntax is called (looks a > bit like shell name expansion syntax), Looks like a very restricted subset of regular expressions. > and I'm not even sure there is an > efficient way to do what I'm asking. Any ideas would be appreciated. import re lines = """ apple1 apple2 apple3_SD formA formB formC kla_MM kla_MB kca_MM """.strip().split() patterns = [ r'apple[12]', r'apple3_SD', r'form[ABC]', r'kla_M[MB]', r'kca_MM', ] for pat in patterns: for line in lines: m = re.match(pat, line) print "%s match %s : %s" % (pat, line, m and "Yes" or 'No') HTH From wildemar at freakmail.de Fri Mar 24 13:40:51 2006 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 24 Mar 2006 19:40:51 +0100 Subject: What's The Best Editor for python In-Reply-To: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> References: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> Message-ID: <44243D33.8060806@freakmail.de> just to bloat this thread some more: Am I the only one using jEdit? (really, I never see it mentioned anywhere ...) wildemar From n.estner at gmx.de Fri Mar 17 15:55:39 2006 From: n.estner at gmx.de (nikie) Date: 17 Mar 2006 12:55:39 -0800 Subject: Linear regression in NumPy Message-ID: <1142628938.982098.239850@u72g2000cwu.googlegroups.com> I'm a little bit stuck with NumPy here, and neither the docs nor trial&error seems to lead me anywhere: I've got a set of data points (x/y-coordinates) and want to fit a straight line through them, using LMSE linear regression. Simple enough. I thought instead of looking up the formulas I'd just see if there isn't a NumPy function that does exactly this. What I found was "linear_least_squares", but I can't figure out what kind of parameters it expects: I tried passing it my array of X-coordinates and the array of Y-coordinates, but it complains that the first parameter should be two-dimensional. But well, my data is 1d. I guess I could pack the X/Y coordinates into one 2d-array, but then, what do I do with the second parameter? Mor generally: Is there any kind of documentation that tells me what the functions in NumPy do, and what parameters they expect, how to call them, etc. All I found was: "This function returns the least-squares solution of an overdetermined system of linear equations. An optional third argument indicates the cutoff for the range of singular values (defaults to 10-10). There are four return values: the least-squares solution itself, the sum of the squared residuals (i.e. the quantity minimized by the solution), the rank of the matrix a, and the singular values of a in descending order." It doesn't even mention what the parameters "a" and "b" are for... From johnjsal at NOSPAMgmail.com Thu Mar 2 16:19:31 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 02 Mar 2006 21:19:31 GMT Subject: do design patterns still apply with Python? In-Reply-To: <1141333305.284973.54620@z34g2000cwc.googlegroups.com> References: <8SINf.1718$No6.40137@news.tufts.edu> <1141333305.284973.54620@z34g2000cwc.googlegroups.com> Message-ID: shandy.b at gmail.com wrote: > In python, you might find it more natural to do design patterns in a > completely different way than they're implemented in Java. For > example, I've heard of using the Singleton pattern in python by just > implementing it as a module, no classes necessary. Yeah, that's what I was wondering. I wonder if, after reading a DP book, I might have to 'unlearn' some things when applying them to Python. But I suppose I should just do it first and then try to implement them myself. OOP is just so mind-bending for me that I've kind of put off patterns right now until I get more comfortable with it. :) From mensanator at aol.com Fri Mar 24 19:05:50 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 24 Mar 2006 16:05:50 -0800 Subject: a problem to solve References: <5oiUf.1818$No6.41433@news.tufts.edu> <1143071664.377833.136660@z34g2000cwc.googlegroups.com> <1143232745.363162.53810@j33g2000cwa.googlegroups.com> <1143237995.862980.135710@i40g2000cwc.googlegroups.com> <1143243662.182759.230130@e56g2000cwe.googlegroups.com> Message-ID: <1143245150.815621.130720@v46g2000cwv.googlegroups.com> Michael Tobis wrote: > Yeah, I misread the question, but the gist of my query remains. > > > The odds are 100% if there is at least one solution. > > Let's not get too philosophical. My question was whether there was an a > priori reason for believing that there is a solution. > > > You want permutations with replacement, so there are 8**4 = 4096 > > Agreed. My mistake. > > >> These will turn on 15 lights in each set of 20, of which the number of > >> possibilities is C(15,20)**4 = 57779667567968256L > > > No, there are only 8 possible patterns on each panel. > > Not every possible 15 lamp pattern is realized > > Right, but that is exactly my point. This is the number of possible > selections of 15 out of 20 made four times. Any attempt will be a > member of that space. Then the probability of hitting a solution at > random is the ratio of solutions to that space. > > So I think my chance of success on a sinlge selection, assuming random > design of the switch banks, is correct: 1.9e-05 My error gave me the > wrong multiplier. It's 4096 rather than 1820. So now I'm goinq with a > 7.79% chance of randomly setting up the problem to yield a solution. Ok, random settings didn't make any sense since the problem was already set up. > > Still seems somwhat unlikely that there would be a solution unless the > problem were set up in advance. It would be easy to set up an answer. Then work backwards to create 7 bad settings for each switch, although I'm not sure how you would ensure not accidently creating another solution. Would be simple enough to verify, though. With only 4096 permutations, it only takes seconds to find the solution(s). > (homework? a puzzle book?), I am just > wondering where the puzzle came from. The OP mentioned it came from a puzzle game That made me think there was likely at least one solution. > > Was there more than one solution? No, there is exactly one solution where Y has 20 1's. Second best has only 16 1's, of which there are 8 solutions. For example: 16 11011011111111110011 3 4 5 5 where the numbers are popcount, Y (in binary) and the four switch settings. > > mt From neurogasm at gmail.com Sat Mar 25 18:18:12 2006 From: neurogasm at gmail.com (Kun) Date: Sat, 25 Mar 2006 18:18:12 -0500 Subject: sending emails to a list of recipients [update] In-Reply-To: References: Message-ID: Kun wrote: > i have the following code: > > ---------------------------------- > import smtplib > > from email.MIMEText import MIMEText > fp = open('confirmation.txt', 'rb') > msg = MIMEText(fp.read()) > > From = 'xxxx at xxxx.xxxx.edu' > > msg['Subject'] = 'Purchase Confirmation' > msg ['From'] = From > msg['To'] = emails > > s = smtplib.SMTP('xxxx.xxx.xxx.edu') > s.login('xxxxx','xxxx') > s.sendmail(msg['From'], msg['To'], msg.as_string()) > s.close() > ---------------------------------- > > it works if msg['To'] = 'email at email.com' > > however, i'm trying to attach a list of emails named 'emails' to msg['To'] > > emails is in the following format: ['nxxx at gmail.com', 'nxxx at gmail.com', > 'xxx at xxx.xxxx.edu'] > > > anyone have an idea how i can modify this script to work with sending a > list? note this is a snippet of a larger code, 'emails' is as a string > defined earlier. this is my error msg of leaving the code in its current state... (brave yourself) Traceback (most recent call last): File "/Tutorial/IMAP/scannermailer.py", line 41, in -toplevel- s.sendmail(msg['From'], msg['To'], msg.as_string()) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/Message.py", line 129, in as_string g.flatten(self, unixfrom=unixfrom) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/Generator.py", line 82, in flatten self._write(msg) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/Generator.py", line 120, in _write self._write_headers(msg) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/Generator.py", line 166, in _write_headers header_name=h, continuation_ws='\t').encode() File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/Header.py", line 395, in encode return self._encode_chunks(newchunks, maxlinelen) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/Header.py", line 355, in _encode_chunks _max_append(chunks, s, maxlinelen, extra) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/quopriMIME.py", line 79, in _max_append L.append(s.lstrip()) AttributeError: 'list' object has no attribute 'lstrip' From larry.bates at websafe.com Wed Mar 8 16:00:13 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 08 Mar 2006 15:00:13 -0600 Subject: sending a text message via webpage button In-Reply-To: <1141794395.277013.245680@e56g2000cwe.googlegroups.com> References: <1141794395.277013.245680@e56g2000cwe.googlegroups.com> Message-ID: <440F45DD.2040106@websafe.com> John wrote: > Can anyone help me in coding a script that can send a text message > typed to > the script like. > > sendmessage 6318019564 "test message" > > What I want to do is fill up this information on this webpage > > http://www.cingularme.com/do/public/send;jsessionid=aKDwXM1S0Reh > > and click the submit button using the python script. Any ideas on > how to do this or if someone has already done this? > > Thanks, > --j > I send text messages by using smtp and sending to: <10-digit cell phone number>@mobile.mycingular.com example 2055551212 at mobile.mycingular.com Is a LOT easier to implement and doesn't depend on the web page not changing. -Larry Bates From vinjvinj at gmail.com Wed Mar 15 16:49:17 2006 From: vinjvinj at gmail.com (vinjvinj) Date: 15 Mar 2006 13:49:17 -0800 Subject: Need advice on reading contents of a file into memory Message-ID: <1142459357.894399.143120@v46g2000cwv.googlegroups.com> f = open(someFilePath, "rb") content = [] for data in content.read() content.append(data) fullContent = "".join(content) Is there a more efficient way of doing this? I'll be running this operation on 10,000+ files where each file is an image file with size 50k-100k From bdesth.quelquechose at free.quelquepart.fr Sun Mar 26 17:13:53 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 27 Mar 2006 00:13:53 +0200 Subject: object references In-Reply-To: <1143351204.139672.36490@i39g2000cwa.googlegroups.com> References: <1143351204.139672.36490@i39g2000cwa.googlegroups.com> Message-ID: <4426e4cf$0$11336$636a55ce@news.free.fr> DrConti a ?crit : > Dear Python developer community, > I'm quite new to Python, so perhaps my question is well known and the > answer too. > > I need a variable alias ( what in other languages you would call "a > pointer" (c) or "a reference" (perl)) Well, that's the only kind of "variable"[1] in Python. [1] the correct name in Python is 'binding', since it's about 'binding' a reference to a name, not labelling an in-memory address and storing data there. > I read some older mail articles and I found that the offcial position > about that was that variable referencing wasn't implemented because > it's considered bad style. > There was also a suggestion to write a real problem where referencing > is really needed. > I have one...: You *think* you have one. > I'm trying to generate dynamically class methods which works on > predefined sets of object attributes. > one of these is the set of attributes identfying uniquely the object > (primary key). > A na?ve attempt to do the job: > > class ObjectClass: > """ Test primary Key assignment """ > > if __name__ == "__main__": > > ObjectClassInstantiated=ObjectClass() > ObjectClassInstantiated.AnAttribute='First PK Elem' > ObjectClassInstantiated.AnotherOne='Second PK Elem' > ObjectClassInstantiated.Identifier=[] > ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnAttribute) > ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnotherOne) > print ObjectClassInstantiated.Identifier > ObjectClassInstantiated.AnAttribute='First PK Elem Changed' > print ObjectClassInstantiated.Identifier > > leads a wrong result > >>./test.py > > ['First PK Elem', 'Second PK Elem'] > ['First PK Elem', 'Second PK Elem'] > --> wrong! It should write ['First PK Elem Changed', 'Second PK Elem'] Nope, it's exactly what you asked for !-) > > i.e. the assgnment > > ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnAttribute) > > assigns only the attribute value, not the reference. 1/ it's not an assignement 2/ it does not store the attribute "value", it stores the reference to the object the attribute is bound to. When you later rebind the attribute, it only impact this binding - there's no reason it should impact other bindings. > so my question is: > is it still true that there is no possibilty to get directly object > references? But object references *are* what you have. > Is there a solution for the problem above ? Yes : keep a reference to the attribute name, not to the value bound to that name. There are many ways to do it, here's one: ObjectClass.Identifier = property( fget=lambda self: [self.AnAttribute, self.AnotherOne] ) and here's another one: ObjectClassInstantiated._identifier_parts = [] # note the use of strings, not symbols ObjectClassInstantiated._identifier_parts.append("AnAttribute") ObjectClassInstantiated._identifier_parts.append("AnotherOne") ObjectClass.Identifier = property( fget=lambda self: [getattr(self, name) \ for name in self._identifier_parts] ) > Thank you for any feedback May I add some ? Your naming conventions are highly unpythonic. We usually use CamelCase for classes names, and (in order of preference) all_lower_with_underscores or mixedCaps for variables/attributes/functions etc. HTH From cito at online.de Fri Mar 3 15:27:55 2006 From: cito at online.de (Christoph Zwerschke) Date: Fri, 03 Mar 2006 21:27:55 +0100 Subject: Proper class initialization In-Reply-To: <1141311369.088711.284720@u72g2000cwu.googlegroups.com> References: <1141311369.088711.284720@u72g2000cwu.googlegroups.com> Message-ID: gry at ll.mit.edu schrieb: > Hmm, the meta-class hacks mentioned are cool, but for this simple a > case how about just: > > class A: > def __init__(self): > self.__class__.sum = self.calculate_sum() > def calculate_sum(self): > do_stuff > return sum_value If you do it like that, Steven's second suggestion was better: class A: def calculate_sum(): do_stuff return sum_value sum = calculate_sum() That's not only easier simpler, it also avoids calling calculate_sum() every time you create an instance. -- Christoph From jedp at ilm.com Tue Mar 28 23:30:22 2006 From: jedp at ilm.com (Jed Parsons) Date: Tue, 28 Mar 2006 20:30:22 -0800 Subject: ldap usage References: <4429E8F9.8030008@ilm.com> Message-ID: Looks like the top of my message got garbled I was trying to say that I'm using ldap for the first time, trying to write a script that authenticates a user against our ldap server. etc. The rest came through. Hope that makes more sense now :) j -----Original Message----- From: python-list-bounces+jedp=ilm.com at python.org on behalf of Jed Parsons Sent: Tue 3/28/2006 5:55 PM To: python-list at python.org Subject: ldap usage Hi, authenticates a user against our ldap server.: User types in name and password, and module sees if name and password check out right with the ldap server. I see that it's pretty straightforward to do this with: import ldap l = ldap.open('our.ldap.server') try: l.bind_s(username, password, ldap.AUTH_SIMPLE) authenticated = True except: authenticated = False But this uses the plaintext of the user's password. Is there a proper way to send a cryptographic hash to the ldap server? Or do I have to negotiate this through an ssl tunnel or something? Thanks for any tips. Cheers! j -- Jed Parsons Industrial Light + Magic (415) 746-2974 grep(do{for(ord){(!$_&&print"$s\n")||(($O+=(($_-1)%6+1)and grep(vec($s,$O++,1)=1,1..int(($_-6*6-1)/6))))}},(split(//, "++,++2-27,280,481=1-7.1++2,800+++2,8310/1+4131+1++2,80\0. What!?"))); -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Tue Mar 21 04:51:15 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Mar 2006 09:51:15 GMT Subject: should os.walk return a list instead of a tuple? References: Message-ID: Ministeyr wrote: > When walking top to bottom, it allows you to choose the directories > you want to visit dynamically by changing the second parameter of the > tuple (a list of directories). However, since it is a tuple, you > cannot use "filter" on it, since it would mean reassigning it: > > for dir_tuple in os.walk('/home'): > dir_tuple[1]=filter(lambda x: not x.startswith('.'), > dir_tuple[1]) > #do not show hidden files > print dir_tuple #just print the directory and its > contents in the > simplest possible way > > If os.walk did return a list of three items instead of a tuple, that > would become possible. But you don't need to assign to it, you simply need to mutate it: for dir, subdirs, files in os.walk('/home'): subdirs[:] = [d for d in subdirs if not d.startswith('.')] print dir, subdirs, files (and if you are desparate to use filter+lambda that works as well.) From johnjsal at NOSPAMgmail.com Wed Mar 8 19:11:12 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Mar 2006 19:11:12 -0500 Subject: is there any overheard with try/except statements? Message-ID: One of the things I learned with C# is that it's always better to handle any errors that might occur within the codes itself (i.e. using if statements, etc. to catch potential out of range indexing) rather than use too many try/catch statements, because there is some overhead every time the program encounters the try. Is this the case at all with Python, in terms of extra work or slower speed? Or is try/except implemented differently in Python than it is in other languages, so that it runs just like any other code? Thanks. From Serge.Orlov at gmail.com Wed Mar 29 11:17:17 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 29 Mar 2006 08:17:17 -0800 Subject: FTP not Returning (Python on Series 60 Nokia) References: <1143618018.661424.234510@v46g2000cwv.googlegroups.com> <1143625131.154921.49980@v46g2000cwv.googlegroups.com> <1143642673.374843.161860@e56g2000cwe.googlegroups.com> <1143646663.438119.12400@v46g2000cwv.googlegroups.com> <1143647254.503722.280380@j33g2000cwa.googlegroups.com> Message-ID: <1143649037.891797.267420@g10g2000cwb.googlegroups.com> mbukhin at gmail.com wrote: > Right. You know I took your suggestion for more print statements and > found the offending line. > > [SNIP] > print "close start" > conn.close() > print "close end" > #return self.voidresp() > print "end of everything" > > self.voidresp() was hanging! Do I need it? I don't keep the whole description of ftp protocol in my memory :) You'd better read the RFC. But I suspect a server is supposed to send some kind of confirmation that the file was successfully written on a disk and a client is supposed to wait for such confirmation. Serge. From mandelin at cs.berkeley.edu Thu Mar 30 14:12:03 2006 From: mandelin at cs.berkeley.edu (Dave Mandelin) Date: 30 Mar 2006 11:12:03 -0800 Subject: GUI in python References: <1143670803.148098.21940@z34g2000cwc.googlegroups.com> Message-ID: <1143745923.363900.134950@e56g2000cwe.googlegroups.com> A friend of mine recently used PythonCard and he found it pretty good. I use wxPython, which is what PythonCard is based on, and I think it's very good, but it's more work to get started with than PythonCard. -- Want to play tabletop RPGs over the internet? Check out Koboldsoft RPZen: http://www.koboldsoft.com From cito at online.de Tue Mar 21 03:40:28 2006 From: cito at online.de (Christoph Zwerschke) Date: Tue, 21 Mar 2006 09:40:28 +0100 Subject: ** Operator In-Reply-To: References: <1142833145.976550.104830@v46g2000cwv.googlegroups.com> <1142833540.860154.137040@u72g2000cwu.googlegroups.com> <1hcgw5p.1ufznwe1lxeagfN%aleaxit@yahoo.com> <1142864492.645457.291240@j33g2000cwa.googlegroups.com> <441ed65c$1_3@newspeer2.tds.net> Message-ID: Christoph Zwerschke wrote: > Kent Johnson wrote: >> The way to make this change happen is to submit a bug report with your >> suggested change. See the link at the bottom of the above page to find >> out how. > > I know, but I wanted to see at least one person assenting before doing > so. Anyway, I took your words as assent and filed a bug report now ;-) ... which was promptly rejected. Seems like the Gods of Python don't want newbies to understand the manuals too easily, so they can have their fun ranting why they did not RTFM, when they come here and ask silly questions. ;-) -- Christoph From benji at benjiyork.com Mon Mar 13 17:45:56 2006 From: benji at benjiyork.com (Benji York) Date: Mon, 13 Mar 2006 17:45:56 -0500 Subject: Localized month names? In-Reply-To: References: Message-ID: <4415F624.1080305@benjiyork.com> Jarek Zgoda wrote: > How do I get a list of localized month names for current locale? The > first thing that came to my mind was an ugly hack: >>> import locale >>> locale.nl_langinfo(locale.MON_1) 'January' -- Benji York From amaltasb at gmail.com Fri Mar 31 23:05:15 2006 From: amaltasb at gmail.com (amaltasb at gmail.com) Date: 31 Mar 2006 20:05:15 -0800 Subject: Pickle or Mysql Message-ID: <1143864315.283697.20970@v46g2000cwv.googlegroups.com> Can I use Pickle to store about 500,000 key value pairs.. or should I use mySql. Which one is best for performance, as the key value pair increases. Thanks From onurb at xiludom.gro Wed Mar 15 14:37:05 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 15 Mar 2006 20:37:05 +0100 Subject: best practices for making read-only attributes of an object In-Reply-To: References: Message-ID: <44186d15$0$31436$626a54ce@news.free.fr> Tim Chase wrote: > I've set up an object and would like to make certain attributes > read-only (or at least enforce it without doing extra work, as per > name-mangling or the like). Ideally, the property would be set in the > __init__, and then not be allowed to change. > > The best solution I've been able to come up with is something of the form: > > > class Foo: old-style classes are deprecated, please use new-style classes: class Foo(object): > def __init__(self, name, value): > self.__dict__['_name'] = name > self.value = value > def __getattr__(self, attr): > name = "_%s" % attr > if name in self.__dict__: return self.__dict__[name] > raise AttributeError, attr > def __setattr__(self, attr, value): > if attr == 'value': > self.__dict__['value'] = value > else: > raise AttributeError, attr > > Is there a better ("more pythonic") way to do this? One usually uses properties withour setter: class Parrot(object): def __init__(self, is_dead): self._is_dead = is_dead is_dead = property(fget=lambda self: self._is_dead) p = Parrot(False) print p, p.is_dead > Particularly if it > plays well with sub-classing Foo. class DeadBlueParrot(Parrot): def __init__(self): self._color = "Blue" Parrot.__init__(self, True) color = property(fget=lambda self: self._color) d = DeadBlueParrot() print d, d.color, d.is_dead HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From aleaxit at yahoo.com Sat Mar 18 20:53:15 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 18 Mar 2006 17:53:15 -0800 Subject: pop3 mail download - using python.org example References: Message-ID: <1hcepn1.1bcj8ml1o0jjl2N%aleaxit@yahoo.com> Kevin F wrote: > i'm trying to this this code to access my pop server but it only prompts > for a password and not a username, how do i get it to ask for my > username as well? getpass.getuser() doesn't prompt, it gets your username from the environment or the OS. If you want a raw input function that prompts, instead of that call rawinput('User: ') ... Alex From alan.franzoni.xyz at gmail.com Tue Mar 14 08:25:32 2006 From: alan.franzoni.xyz at gmail.com (Alan Franzoni) Date: Tue, 14 Mar 2006 14:25:32 +0100 Subject: Which GUI toolkit is THE best? References: <441172c2$1@news1.ethz.ch> <1142273736.875873.266880@e56g2000cwe.googlegroups.com> <7xy7zenr6u.fsf@ruckus.brouhaha.com> <1142276145.151066.90280@j33g2000cwa.googlegroups.com> Message-ID: <104933wtccrd2$.icd1ludciy4f$.dlg@40tude.net> Paul Boddie on comp.lang.python said: > Now, since the commercial licence is "per developer", some cunning > outfit could claim that only one developer wrote their product (rather > than one hundred developers, say), but this would be a fairly big > breach of trust (although nothing unusual in the world of commerce, I'm > sure). Would a business making software for other such businesses care > about such things? What kind of recourse would they have? Just one thing I don't understand: if you're developing all your software inside your company, how would they know if you already coded it or you still have to? Also, couldn't a big company buy a *single* commercial license from the beginning, build a software employing hundreds of developers using the GPL license, and then distribute the software pretending that the single developer had done everything? This would hit Trolltech anyway. I think the problem has to do with the QT license system. It's their problem, not a developer's one. Also, I suppose one of their commercial licenses provides with far lot more than a license - e.g. I think they'll offer support, design tools, additional docs and libraries. And what would then be their income if they refused to sell you a commercial license because they *know* you've already coded your app using the GPL license of Qt? You could simply throw away your app and never distribute it, and they would'nt see a cent anyway. Personally, I don't like Qt licensing, since I think there're good widget sets around that don't have such limitations, but I don't think that people at Trolltech are really trolls :-= -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Rremove .xyz from my address in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From fredrik at pythonware.com Wed Mar 22 02:10:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Mar 2006 08:10:15 +0100 Subject: doctest, unittest, or if __name__='__main__' References: <1142974528.143287.326360@e56g2000cwe.googlegroups.com> <1142976616.012029.140050@t31g2000cwb.googlegroups.com> Message-ID: john_sips_tea at yahoo.com wrote: > Well, since this is a mailing list where this sort of thing is > discussed, and since I was was asking about which way > is preferred, could you tell us why you (presumably) think > doctest is vastly superior to unittest? doctest comes with extensive documentation, which, among other things, discuss the advantages of using doctest. have you read the documentation ? http://www.python.org/doc/lib/module-doctest.html > > don't you have better things to do with your time ? > > That wasn't very friendly. so you think that a "why all this creativity when you could just standardize on something ported from java, and throw away every- thing else" post is friendly ? really ? > Anyhow, I'm not attacking doctest, but rather, just trying > to understand why there seems to be two very similar ways > of testing your code built into the system (considering that > one motto around here is "There should be one -- and > preferably only one -- obvious way to do it."). if you think that motto means that there should be only one non- deprecated solution to any higher-level problem, you've completely and utterly missed the point. From bignose+hates-spam at benfinney.id.au Thu Mar 23 16:48:56 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 24 Mar 2006 08:48:56 +1100 Subject: An Efficient Scalar Class in Python References: <1143093971.652491.98600@z34g2000cwc.googlegroups.com> Message-ID: <87acbgq1br.fsf@rose.polar.local> "uymqlp502 at sneakemail.com" writes: > A Python class was designed to represent physical scalars and to > eliminate errors involving implied physical units (e.g., confusing > angular degrees and radians). This sounds like a useful abstraction; I'm not sure if there are established ways to do this, but I'd like to see something like this in PyPI. > Give it a try. If you do scientific or engineering computation, I > bet you'll like it! > > http://RussP.org/scalar.htm I think you'll have more uptake if you: - make a distutils 'setup.py' for easy install/uninstall - submit to PyPI so it's easily found and installed over the net Please ask here, or contact me directly (email address munged) if you want assistance with doing these steps. -- \ "You know I could rent you out as a decoy for duck hunters?" | `\ -- Groucho Marx | _o__) | Ben Finney From aleaxit at yahoo.com Sun Mar 26 10:21:23 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Mar 2006 07:21:23 -0800 Subject: SSH, remote login, and command output References: Message-ID: <1hcsp62.11bpa0d19zmykcN%aleaxit@yahoo.com> Spire 01 wrote: > Greetings! > > I'm working on a Python program for a small LAN of Linux systems running > Gentoo, and I need a little help figuring out what I need to do it. So what > I'd like to do is, from any given computer, log on to every other computer, > run a certain command (which normally outputs text to the terminal), and > store the output so I can use the aggregate statistics later in the program. OK... > I would normally something along the lines of SSH to do it, but I don't > know what I would need to pull that off in Python. There's also one SSH is a good protocol, and a good Python implementation of that is Paramiko, http://www.lag.net/paramiko/ . Twisted also includes SSH protocol implementations, and it's a great way to do networking. > complication: the systems could be Gentoo systems, or they could be logged > into Windows since they're dual booted. Considering all of this, can anyone There are sshd (ssh-server) implementations for Windows, though I have no experience installing those -- you'll have to download the free ones and give them a try. Alternatively, you might write a Twisted-based SSH server in Python, though, from what I recall, making Windows Services with Python, while possible, isn't quite trivial. Once you're SSH-connected to a machine and don't know whether it's on Windows or Linux, it shouldn't be hard to find out -- just run a command that gives different output in each case, and proceed accordingly. > give me some recommendation as to what library I should learn how to use to > pull this off? I admit, I haven't done too much in the way of networks, but > if someone can tell me what I need to do remote logins in this way, I'll do > what I can to make it work. Twisted may be a bit heavy going if you have no network programming experience, so I suggest you first try ensuring all machines have sshd (==are able to accept SSH logins) and set up the needed passwords (for Unix and MacOSX, this means running ssh-keygen once, placing the public key in the .ssh directory right under the home of the user to which you'll be logging in remotely on each machine, and the private key in the machine you'll be logging in _from_ -- not sure how the various sshd implementations for Windows work) -- trying it all with the ssh client from the command line first, and then moving to paramiko. Twisted would ensure better scalability, but if the LAN _stays_ small that may in fact not matter. Alex From steve at REMOVETHIScyber.com.au Wed Mar 1 17:17:01 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 02 Mar 2006 09:17:01 +1100 Subject: Is it better to use class variables or pass parameters? References: <1141241522.096240.53380@v46g2000cwv.googlegroups.com> Message-ID: On Wed, 01 Mar 2006 11:32:02 -0800, Derek Basch wrote: > This one has always bugged me. Is it better to just slap a "self" in > front of any variable that will be used by more than one class method > or should I pass around variable between the methods? That depends on whether the variable is conceptually an attribute of the instance or a parameter. Attributes of the instance should be made instance attributes by (as you put it) slapping a "self" in front of it. Parameters of the methods should be passed around as arguments to the methods. -- Steven. From usenetpublic-elessar.xyz at yahoo.it Sat Mar 11 22:07:44 2006 From: usenetpublic-elessar.xyz at yahoo.it (EleSSaR^) Date: Sun, 12 Mar 2006 04:07:44 +0100 Subject: "RuntimeError: dictionary changed size during iteration" ; Good atomic copy operations? References: <104lhpbuofu4l.jz32d3oa1uk7$.dlg@40tude.net> <11qri29hja4g5$.nxe858qnxam4.dlg@40tude.net> Message-ID: <1r5e00ku8lwsw$.1witcp6a4tec6$.dlg@40tude.net> robert si ? profuso/a a scrivere su comp.lang.python tutte queste elucubrazioni: > Yes, a "backup" / autosave while all threads are running. It doesn't > matter if 'before' of 'after' another item has been added/deleted > atomically. But it does matter if the autosave happens *while* an item is being updated, I suppose. E.g. if a single 'atomic' operation would change two dictionaries, and an autosave triggers after the first has been changed and the second hasn't, this would be an unwanted autosave, right? >> By the way, you could try employing locks from other threads to dump the >> object as well... this would prevent additional locking. > > Don't understand. > The threads work all simulatniously on the object tree, add and detach > atomically only valid sub-trees. You're never using any lock, then? Isn't it possible that two threads try changing the very same dict/list at the same time? Just one more question: are you running your software on a single-cpu machine? > change "subobj.x='y'" is a dictionary operation. That would make > threaded programming very arduous. Well... threaded programming usually is a hard task. No surprise so many people prefer async programming nowadays. It makes many things simpler. > def rt_save_dict_copy() > tod={} > for k in fromd.keys(): > try: tod[k]=fromd[k] > except: pass > return tod > > without true iteration over the original dict whould copy without > RuntimeError. But with no warranty of data consistency. It will prevent new values to be computed, but if one value from the dict is modified during iteration, the dict may be left in a never-existed state: import random random.seed() fromd = {1:1, 2:2, 3:3, 4:4, 5:5} print "dict before iteration:", fromd def rt_save_dict_copy(): tod={} for k in fromd.keys(): try: tod[k]=fromd[k] except: pass fromd[random.choice(xrange(1,6))] = random.choice(xrange(1,10)) return tod print "copied dict:", rt_save_dict_copy() print "dict after copy:", fromd -- EleSSaR^ -- Togli .xyz dalla mia email per contattarmi. From lucaberto at libero.it Thu Mar 2 10:03:51 2006 From: lucaberto at libero.it (luca72) Date: 2 Mar 2006 07:03:51 -0800 Subject: Pyserial never read In-Reply-To: References: <1140105936.408387.88130@z14g2000cwz.googlegroups.com> <1140219414.143448.234450@z14g2000cwz.googlegroups.com> <1140302110.028540.176210@g43g2000cwa.googlegroups.com> <1140599901.082142.262540@f14g2000cwb.googlegroups.com> <1140700256.017002.177580@f14g2000cwb.googlegroups.com> <8frrv117h4ca9pfft1s2e4la64u241mrnb@4ax.com> Message-ID: <1141311831.208416.218100@i39g2000cwa.googlegroups.com> Hello i how can set with pyserial the following data? > byte delay= 40000 > serial control line: > dtr = high > rts= low Thanks Luca From bignose+hates-spam at benfinney.id.au Thu Mar 23 17:09:20 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 24 Mar 2006 09:09:20 +1100 Subject: Function params with **? what do these mean? References: <1142887602.977736.300990@u72g2000cwu.googlegroups.com> <4422fd92@nntp0.pdx.net> Message-ID: <8764m4q0dr.fsf@rose.polar.local> Scott David Daniels writes: > At the risk of being thought of as beating a dead horse, this was a > _great_ way to ask this question. [...] > So, anyhow, thanks for taking the time to write your question properly. Take that risk, please. There's enough lambasting of (and probably much more private grumbling over) poor delivery of questions, but not enough praise when *good* form is followed. The latter does much more to show what we consider appropriate. -- \ "Ice Water? Get some onions - that'll make your eyes water!" | `\ -- Groucho Marx | _o__) | Ben Finney From paul at boddie.org.uk Sat Mar 11 06:22:42 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Mar 2006 03:22:42 -0800 Subject: Cheese Shop -> BSOL? References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> <1142039514.707128.240270@j33g2000cwa.googlegroups.com> Message-ID: <1142076162.193533.80540@v46g2000cwv.googlegroups.com> Tim Churches wrote: > Would it be possible to rename "Cheese Shop" as "Bright Side of Life"? Well, you could replay the conversation I gave as an example elsewhere to see if it sounds ridiculous or not, but what we've encountered here is the problem of whether something should be given a distinctive identity or a derivative identity. A long time ago, and possibly continuing to this day, people complained about how nearly every Python package, module or program had names starting or ending with "Py" - announcing a module in a Python newsgroup and giving it a name starting with "Py" seemed somewhat redundant, and there was always the issue of not being able to scan long lists of packages comfortably, just like with all the KDE application names that start with the letter K. But even without "the curse of Py", many people don't just choose arbitrary names for their packages: it often makes sense to include related technologies in the name (eg. XML, XSLT, ado, dav), or to use a descriptive component, possibly in shortened form (eg. auth, bayes, bio, Cal). Yes, a search will often bring forth the right resource regardless of what it's called, but many people underestimate their own searching skills and overestimate what other people can find via things like Google. Of course, programs may downplay Python as the implementation technology because the underlying technical details are mostly irrelevant to end-users (eg. BitTorrent, b3, Eric, Glarf), but if we look at distinctively named packages, we can see that they often attempt to define their own identity distinct from Python (eg. BeautifulSoup, Dabo, DejaVu, Django, Twisted, Zope), frequently because they seek to be the primary point of reference for developers - developing in Twisted or Zope is more specialised than just developing things in Python. Some of the distinctively named package names employ metaphors and/or cultural references that possibly make them more memorable, but they don't necessarily make the names easy to guess. So should a service for finding Python packages have a distinct identity? It is possible that a package index could be someone's principal view of the Python world ("I go to Camelot to get... what is it I get there?"), but the things that emerge from such a service aren't just downloads that have little in common with each other. Consequently, I don't think a descriptive name, derived from the name of the technology, is sensibly avoided in this case. Paul From felipe.lessa at gmail.com Fri Mar 31 19:01:05 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 31 Mar 2006 21:01:05 -0300 Subject: Exception handling....dumb question? In-Reply-To: <1143849093.457940.294150@g10g2000cwb.googlegroups.com> References: <1143849093.457940.294150@g10g2000cwb.googlegroups.com> Message-ID: <1143849665.3988.1.camel@kenshin> Em Sex, 2006-03-31 ?s 15:51 -0800, kbperry escreveu: > Is there a way to show what error it is throwing? > > Like in Java, you can do > catch (Exception e){ > System.out.println(e); > } > > Is there an equivalent way to do this in Python? >>> try: ... print 1/0 ... except Exception, e: ... print '*', e.__class__, '*' ... print '*', e, '*' ... * exceptions.ZeroDivisionError * * integer division or modulo by zero * -- Felipe. From __peter__ at web.de Sat Mar 11 05:32:00 2006 From: __peter__ at web.de (Peter Otten) Date: Sat, 11 Mar 2006 11:32:00 +0100 Subject: Inconsistency of special class method lookup? References: <1142070795.665106.10690@v46g2000cwv.googlegroups.com> Message-ID: anne.nospam01 at wangnick.de wrote: > class Foo(object): > ????????def __len__(): return 2 > ????????__len__ = staticmethod(__len__) > print len(Foo) > >>> > Traceback (most recent call last): > ??File?"C:/Dokumente?und?Einstellungen/All?Users/Dokumente/foo.py", > line 4, in ? > ????print?len(Foo) > TypeError: len() of unsized object > > However, the following works: > > class FooType(type): > ????????def __len__(self): return self.l() > class Foo(object): > ????????__metaclass__ = FooType > ????????def l(): return 3 > ????????l = staticmethod(l) > print len(Foo) > >>> > 3 > > Any good reason why the lookup process doesn't find __len__ as > staticmethod of the class? Special methods of newstyle objects are always looked up in the class, and the class of a class is its metaclass. Therefore len(Foo()) invokes type(Foo()).__len__ which is the same as Foo.__len__ and len(Foo) invokes type(Foo).__len__ which (in your example) is the same as FooType.__len__. Peter From neurogasm at gmail.com Sat Mar 25 15:53:47 2006 From: neurogasm at gmail.com (Kun) Date: Sat, 25 Mar 2006 15:53:47 -0500 Subject: simple string search and replace Message-ID: hey guys, here's my code, senders = [('460 (BODY[HEADER.FIELDS (FROM)] {46}', 'From: Friend \r\n\r\n'), ')', ('462 (BODY[HEADER.FIELDS (FROM)] {37}', 'From: Kun \r\n\r\n'), ')'] print senders parsed_senders = [] sender = "" for item in senders: if isinstance(item,tuple): item= ''.join(item) if item==')': parsed_senders.append(sender[sender.find('<')+1:].strip()) sender = "" else: sender+=item print parsed_senders wondering if anyone knows how i can remove the '>'s from the list, which outputs to something like ['anon at anon.wharton.com>', 'neurogasm at gmail.com>'] From rtilley at vt.edu Thu Mar 9 11:17:48 2006 From: rtilley at vt.edu (rtilley) Date: Thu, 09 Mar 2006 11:17:48 -0500 Subject: Python Evangelism In-Reply-To: References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> Message-ID: Andrew Gwozdziewycz wrote: > On 3/9/06, rtilley wrote: > > >>>Doug Bromley wrote: >>> >>>>I can see Ruby overtaking Python if we don't ALL do something about it. >> >>I think it's the name. Python. Let's change it to something nicer. Think >>about it... if you found a Ruby, you'd pick it up and put it in your >>pocket. If you ran across a Python, you'd run away. > > > Woah, are you actually serious? What would changing the name of language you're > trying to market do for the marketing campaign? Yes I am. But I'm no one so there is no need to take my advice :) Snakes are naturally thought of as bad or dangerous. Some large snakes eat our pets and other small, warm-blooded, furry mammals like us. People naturally kill snakes or run from them. We teach children to avoid snakes. It's almost instinct to fear them. So, you have a product, an idea, a method... don't name it after something that is so naturally repulsive. It's really that simple. I've had people ask about the "Python" folder on their computer. They thought it must be a virus or malware simply based on its name. From i.g.j.v.d.sangen at student.tue.nl Sun Mar 19 10:34:46 2006 From: i.g.j.v.d.sangen at student.tue.nl (Ivo van der Sangen) Date: Sun, 19 Mar 2006 15:34:46 +0000 (UTC) Subject: Relative paths in mod_python Message-ID: I was wondering if I could use relative paths in a mod_python script. At the moment I am defining a constant string "/path/to/dir/where/script/resides". The problem with this is that when I move the script including files I use to get metadata I have to change this variable. The same problem occurs when I distribute the script; the person using it will first have to modify it, which is not what I want. Is it possible that a mod_python script has as current working directory the directory where the script resides? At the moment os.getcwd() returns '/'. From fakeaddress at nowhere.org Wed Mar 8 10:34:49 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 08 Mar 2006 15:34:49 GMT Subject: Reading binary from a file... In-Reply-To: <1141797306.053658.253950@p10g2000cwp.googlegroups.com> References: <1141797306.053658.253950@p10g2000cwp.googlegroups.com> Message-ID: KraftDiner wrote: [...] > In python I'm able to read in binary data from a file. [...] > > However the data is 16bits per sample and python is storing the > data in a string. How do I convert that 8bit data into a list of 16 > bit integers? On the vast majority of systems, files hold sequences of eight-bit integers. How you convert from those to your 16-bit type depends on how the the writer of the file converted the 16-bit integer type to a sequence 8-bit integers. -- --Bryan From scott.daniels at acm.org Thu Mar 9 19:21:13 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 09 Mar 2006 16:21:13 -0800 Subject: First script, please comment and advise In-Reply-To: <1141936961.472567.53070@p10g2000cwp.googlegroups.com> References: <1141917596.011498.311500@p10g2000cwp.googlegroups.com> <1141936961.472567.53070@p10g2000cwp.googlegroups.com> Message-ID: <4410c473$1@nntp0.pdx.net> bearophileHUGS at lycos.com wrote: >> nested and hided inside a class. > > Hidden, sorry :-) > > >> Can a "sub-function" be called directly from outside the defining function? No, and each call to scramble_text defines a new function "scramble". Further, there is no way to unit test "scramble". --Scott David Daniels scott.daniels at acm.org From dd55 at cornell.edu Fri Mar 17 10:33:12 2006 From: dd55 at cornell.edu (Darren Dale) Date: Fri, 17 Mar 2006 10:33:12 -0500 Subject: How do I use the subprocess module with mswindows? Message-ID: I'm a developer on the matplotlib project, and I am having trouble with the subprocess module on windows (Python 2.4.2 on winXP). No trouble to report with linux. I need to use _subprocess instead of pywin32, but my trouble exists with either option: import subprocess process = subprocess.Popen(['dir'], stderr=subprocess.STDOUT, stdout=subprocess.PIPE) stat = process.wait() print process.stdout.read() ---------------------------------------------------------------------- Traceback (most recent call last): ? File "C:\Documents and Settings\Darren\Desktop\subprocess_test.py", line 3, in ? ? ? process = subprocess.Popen(['dir'], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)#, stdout=PIPE) ? File "C:\Python24\lib\subprocess.py", line 533, in __init__ ? ? (p2cread, p2cwrite, ? File "C:\Python24\lib\subprocess.py", line 593, in _get_handles ? ? p2cread = self._make_inheritable(p2cread) ? File "C:\Python24\lib\subprocess.py", line 634, in _make_inheritable ? ? DUPLICATE_SAME_ACCESS) TypeError: an integer is required ---------------------------------------------------------------------- If I change my script a bit, I get a different error: import subprocess process = subprocess.Popen(['dir']) stat = process.wait() print process.stdout.read() ---------------------------------------------------------------------- Traceback (most recent call last): ? File "C:\Documents and Settings\Darren\Desktop\subprocess_test.py", line 3, in ? ? ? process = subprocess.Popen(['dir'])#, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)#, stdout=PIPE) ? File "C:\Python24\lib\subprocess.py", line 542, in __init__ ? ? errread, errwrite) ? File "C:\Python24\lib\subprocess.py", line 706, in _execute_child ? ? startupinfo) WindowsError: [Errno 2] The system cannot find the file specified ---------------------------------------------------------------------- Can anyone tell me what I am doing wrong? Thanks, Darren From cjw at sympatico.ca Tue Mar 14 10:54:47 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 14 Mar 2006 10:54:47 -0500 Subject: [Numpy-discussion] [ANN] NumPy 0.9.6 released In-Reply-To: <44168767.80803@ieee.org> References: <44168767.80803@ieee.org> Message-ID: <4416E747.306@sympatico.ca> Travis Oliphant wrote: > This post is to announce the release of NumPy 0.9.6 which fixes some > important bugs and has several speed improvments. > > NumPy is a multi-dimensional array-package for Python that allows > rapid high-level array computing with Python. It is successor to both > Numeric and Numarray. More information at http://numeric.scipy.org > > The release notes are attached: > > Best regards, > > NumPy Developers > > - __array_finalize__ is now called for every array sub-class creation. > > Thanks. What are the parameters for this method and what does it do? How does it differ from the common Python usage of __new__ followed by __init__? [Dbg]>>> Help on built-in function __array_finalize__: __array_finalize__(...) Colin W. From steve at holdenweb.com Mon Mar 20 12:12:07 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 20 Mar 2006 17:12:07 +0000 Subject: whats your favourite object relational mapper? In-Reply-To: <1142873279.311421.325650@i39g2000cwa.googlegroups.com> References: <1142801641.638791.148370@e56g2000cwe.googlegroups.com> <1142819539.741782.189420@v46g2000cwv.googlegroups.com> <1142835121.089445.236070@v46g2000cwv.googlegroups.com> <1142873279.311421.325650@i39g2000cwa.googlegroups.com> Message-ID: Jonathan Ellis wrote: > Giovanni Bajo wrote: > >>Jonathan Ellis wrote: >> >> >>>... which, of course, goes to show how stupid a metric this is, now >>>that even Ian Bicking has admitted that SqlObject in its current form >>>is a dead end. >> >> >>Got a pointer? > > > http://blog.ianbicking.org/sqlobject-2.html > I think describing this as Ian saying the code in its current form "is a dead end" is to read rather more into the words than is actually there. I spoke to Ian, because he made the blog entry the same day as I was using SQLObject as an ORM exemplar in my "Using Databases in Python" tutorial, and I wanted a few words of reassurance. You will find as SQLObject 2 appears that it's more of a refactoring than a complete revision. I suspect the maintenance of the code had become tedious because it had slowly morphed into a less-than-ideal form for its fully-developed functionality. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From kent at kentsjohnson.com Sun Mar 19 09:18:45 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sun, 19 Mar 2006 09:18:45 -0500 Subject: Counting number of each item in a list. In-Reply-To: <1142774630.426660.19970@t31g2000cwb.googlegroups.com> References: <1142772092.958602.272260@e56g2000cwe.googlegroups.com> <441d58f7$0$13046$626a54ce@news.free.fr> <1142774630.426660.19970@t31g2000cwb.googlegroups.com> Message-ID: <441d6342$1_3@newspeer2.tds.net> sophie_newbie wrote: > Hey Bruno, > > I got an invalid syntax error when i tried using your "str_counts = > dict((s, str_list.count(s) for s in set(str_list))" bit of code? Maybe > there is a missing bracket or comma? Or maybe I need to import > something. It should be str_counts = dict((s, str_list.count(s)) for s in set(str_list)) or for Python < 2.4 str_counts = dict([(s, str_list.count(s)) for s in set(str_list)]) Note that this solution iterates str_list once for each element of str_list - the call to count traverses the entire list to create the count. I expect Paul Rubin's solution will be dramatically faster for large lists as it only iterates str_list once. Kent From gongcheng_g at hotmail.com Thu Mar 23 05:54:46 2006 From: gongcheng_g at hotmail.com (ChengGong) Date: 23 Mar 2006 02:54:46 -0800 Subject: Probelem about image size and dimensions In-Reply-To: <48fbg4Fjqn9hU1@uni-berlin.de> References: <1143109000.672508.175070@t31g2000cwb.googlegroups.com> <48fbg4Fjqn9hU1@uni-berlin.de> Message-ID: <1143111286.875298.277290@z34g2000cwc.googlegroups.com> Thank you for your reply. I have been learning python only 2 weeks. According what u said. I tried to import Image but there 's an error on the server. here is the message Error Type: ImportError Error Value: import of "Image" is unauthorized From seberino at spawar.navy.mil Tue Mar 7 17:21:07 2006 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 7 Mar 2006 14:21:07 -0800 Subject: Any advantage in LISPs having simpler grammars than Python? Message-ID: <1141770067.041526.292360@p10g2000cwp.googlegroups.com> Is there any advantage to a language having a nice mathematically compact grammar like LISP does? (or at least used to?) Many have admired the mathematically simple grammar of LISP in which much of the language is built up from conses IIRC. Python's grammar seems complicated by comparison. Is this anything to worry about? Chris From andre.roberge at gmail.com Wed Mar 8 16:46:26 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 8 Mar 2006 13:46:26 -0800 Subject: using PyShell, or other shells? In-Reply-To: References: Message-ID: <1141854386.890894.152660@j52g2000cwj.googlegroups.com> John Salerno wrote: > I'm interested in trying out shells other than IDLE, and I found > PyShell, but I'm not sure how to get it exactly. Is there a way to get > it without installing wxPython, or is it a part of it? I can't find much > reference to it in any of the manuals at wxpython.org (except for a > brief description of what it is, but not *where* it is or how to use it). > PyShell is, as far as I know, now included only as part of wxPython. wxPython includes other little apps that embed PyShell in them. If you do download wxPython to use Pyshell, you may want to download Lightning Compiler, a little app I wrote that embeds PyShell. It can be found at http://sourceforge.net/project/showfiles.php?group_id=125834 under "lightning". Others have found it useful :-) Andr? > Thanks. And if there are other shells that are newer/better, I'd > appreciate a recommendation. From http Thu Mar 2 23:10:41 2006 From: http (Paul Rubin) Date: 02 Mar 2006 20:10:41 -0800 Subject: slicing the end of a string in a list References: <1141357052.436244.24670@i39g2000cwa.googlegroups.com> Message-ID: <7xy7zs88xq.fsf@ruckus.brouhaha.com> John Salerno writes: > > print [line[:-1] for line in open('C:\\switches.txt')] > > Hmm, I just realized in my original code that I didn't escape the > backslash. Why did it still work properly? The character the backslash isn't special: \s doesn't get into a code like \n, so the backslash is passed through. Best not to rely on that. The preferred way to remove the newline is more like: for line in open('C:\\switches.txt'): print line.rstrip() the rstrip method removes trailing whitespace, which might be \n on some systems, \r\n on other systems, etc. > And do I not need the 'r' parameter in the open function? No you get 'r' by default. If you want to write to the file you need to pass the parameter. From benji at benjiyork.com Thu Mar 9 08:59:23 2006 From: benji at benjiyork.com (Benji York) Date: Thu, 09 Mar 2006 08:59:23 -0500 Subject: why no block comments in Python? In-Reply-To: <200603081919.42490.hancock@anansispaceworks.com> References: <_MCPf.1749$No6.40293@news.tufts.edu> <1141843360.140692.44180@i39g2000cwa.googlegroups.com> <200603081919.42490.hancock@anansispaceworks.com> Message-ID: <441034BB.3060003@benjiyork.com> Terry Hancock wrote: > I'm thinking this might be a use-case for the new support for > doctests in a separate file. Having doctests in their own file is (IMHO) a majorly under appreciated feature of doctest. The ability to do either nice user (as in developer) docs with known good examples or well documented not-meant-for-documentation unit/functional/integration tests is terrific. -- Benji York From roy at panix.com Fri Mar 10 11:24:18 2006 From: roy at panix.com (Roy Smith) Date: Fri, 10 Mar 2006 16:24:18 +0000 (UTC) Subject: Why python doesn't use syntax like function(, , x) for default parameters? References: <44115054$0$14937$834e42db@reader.greatnowhere.com> Message-ID: Antoon Pardon wrote: >Do you have trouble remembering that range(n) is actually providing the >second parameter to the function and what it does? Yes. I don't use range() everyday, and it's very rare that I use more than one argument. I do remember that there are additional (optional) arguments to range which alter the sequence (start point and step), but I certainly don't remember which is which. If I needed to use it, I would go look it up. On the other hand, if I saw "range (10, step=2)" written, it would be immediately obvious what was going on without need to refer to the docs. From deets at nospam.web.de Fri Mar 10 19:53:56 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 11 Mar 2006 01:53:56 +0100 Subject: lighter weight options to Python's logging package? In-Reply-To: References: <17426.1316.38093.513429@montanaro.dyndns.org> <20060310230717.GA17067@activestate.com> Message-ID: <47eld3Ff8tfcU1@uni-berlin.de> > We've done a bit already. I will see if there's more we can do. Our use of > the package is actually very simple. All we do are log basic messages. Our > Formatter instance includes the time, level and message. That's it. We > have no need for displaying exception info, don't do threads, don't mess > with the file or module names, etc. The only thing we do that isn't > supported directly by the package is to use a compressing version of the > RotatingFileHandler class. In java's log4j a common idiom for logging is this: if(logger.isDebugEnabled()) { logger.debug(some_lengthy_calculation()); } I never tried to employ that in python - but maybe it would help you too, as it certainly rids you of all unnecessary processing of messages that wouldn't make it anyway. Diez From lucaberto at libero.it Thu Mar 30 01:31:35 2006 From: lucaberto at libero.it (luca72) Date: 29 Mar 2006 22:31:35 -0800 Subject: excel application In-Reply-To: <1143674698.625375.46650@e56g2000cwe.googlegroups.com> References: <1143644666.914943.121390@i40g2000cwc.googlegroups.com> <1143674698.625375.46650@e56g2000cwe.googlegroups.com> Message-ID: <1143700295.279532.271970@e56g2000cwe.googlegroups.com> Thanks Peter Regards Luca From deets at nospam.web.de Tue Mar 28 08:25:06 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 28 Mar 2006 15:25:06 +0200 Subject: embed notepad into a frame widget References: <122hotpiojvre6b@corp.supernews.com> Message-ID: <48srstFl629bU1@uni-berlin.de> Matt wrote: > all, > > trying to load an application (notepad for instance) and have it sit > inside a Python application window. When the main window maximises or > minimises, the (notepad) app follows. > > I am pretty sure I need to use a frame widget under tkinter (win32) but > not exactly sure how to do it. You are pretty wrong being sure :) Under windows, it is indeed possible to embed certain applications into others - the related technical term is conveniently called OLE (Object lining and embedding). But the application has to be prepared for doing so - and this is deep windows stuff, so I guess you can't do that with Tkinter. Another technique is to use so-called activex-controls. The IEfor instance is available as such a control. But that also isn't doable with Tkinter (AFAIK, I'm not totally sure on that). But wxPython can: http://www.wxpython.org/MigrationGuide.html Diez From totalgeekdom at gmail.com Sun Mar 19 20:17:39 2006 From: totalgeekdom at gmail.com (totalgeekdom at gmail.com) Date: 19 Mar 2006 17:17:39 -0800 Subject: System Information In-Reply-To: <1142814987.299021.7380@i39g2000cwa.googlegroups.com> References: <1142814987.299021.7380@i39g2000cwa.googlegroups.com> Message-ID: <1142817459.370098.48660@j33g2000cwa.googlegroups.com> I'm not sure about osx, but I know linux uses a proc virtual filesystem. ( freebsd is probably closer, and it doesn't either but you can mount it via mount_linprocfs none /proc) But if you know if you have a proc file system, you can check it to see if you are under power... IE if I remember right, on my laptop it would be '/proc/acpi/battery/BAT1' >From there I would grep / sed it until I got the results I wanted, then do if os.popen("cat /proc[...]") == 'power': [program] else: print "not plugged in" Not the prettiest of solutions, but it's worth a shot From jstroud at ucla.edu Wed Mar 15 18:32:56 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 15 Mar 2006 15:32:56 -0800 Subject: Python compiler In-Reply-To: References: Message-ID: Rc wrote: > Hello everybody > I'm a newbie, fromBelgium. > My question is where can I find a compiler for free. > For Windows XP. > Thanks > Roger > Sorry for my English > > You might want to look at pyinstaller and inno setup. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From aleaxit at yahoo.com Sun Mar 19 18:35:44 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 19 Mar 2006 15:35:44 -0800 Subject: cmp() on integers - is there guarantee of returning only +-1 or 0? References: <441dd94c$0$20108$834e42db@reader.greatnowhere.com> Message-ID: <1hcgdyo.esncruoxbnavN%aleaxit@yahoo.com> wrote: > def sign(n): > return n and n/abs(n) or 0 > > Whoops... Make that > > def sign(n): > return n and n/abs(n) or 1 Uh? I thought part of the specs was that sign(0) is 0... Alex From ruby at no.spam Sun Mar 12 11:13:43 2006 From: ruby at no.spam (Michal Kwiatkowski) Date: Sun, 12 Mar 2006 17:13:43 +0100 Subject: Why property works only for objects? In-Reply-To: <1hc1q2d.44bzrca7iz86N%aleaxit@yahoo.com> References: <1hbyfgj.a3p39r1smomavN%aleaxit@yahoo.com> <4412107a$0$22499$636a55ce@news.free.fr> <1hbzzh7.1qlkv8hokpiqzN%aleaxit@yahoo.com> <1hc1abj.1fokrj9826uvjN%aleaxit@yahoo.com> <1hc1fgy.5nq08nvj7qkaN%aleaxit@yahoo.com> <1hc1q2d.44bzrca7iz86N%aleaxit@yahoo.com> Message-ID: Alex Martelli napisa?(a): >> Can you also check my reasoning for getting attributes? >> >> value = obj.attr >> * if instance class has __getattribute__, call it >> * else: lookup "attr" in all parent classes using class __mro__; >> if it's a descriptor call its __get__ method, return its value >> otherwise (when descriptor doesn't have __get__, it's unreadable >> and AttributeError is raised) >> * else: check instance __dict__ for "attr", return it when found >> * else: lookup __getattr__ in instance class and call it when found >> * else: raise AttributeError > > No, the value found in the instance (your second 'else' here) takes > precedence if the descriptor found in the first 'else' is > non-overriding. Oh, right. My mistake comes from the subtle difference between defining descriptor as a class and by property() builtin (I've tested only second option and assumed that descriptor without __set__ cannot be rebinded): class non_overriding(object): def __get__(*a): return 12 class C(object): x = non_overriding() y = property(lambda s:23) c = C() c.x = 4 print c.x # => 4 c.y = 5 # => AttributeError: can't set attribute IMHO that's not very consistent. Well, probably some code rely on this, so I just have to live with it. Thanks for your time and patience in explaining my doubts. 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 google03 at sigfpe.com Thu Mar 16 20:46:20 2006 From: google03 at sigfpe.com (Dan Piponi) Date: 16 Mar 2006 17:46:20 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: <1142556358.098924.59180@e56g2000cwe.googlegroups.com> References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <8764medlhm.fsf@qrnik.zagroda> <1142556358.098924.59180@e56g2000cwe.googlegroups.com> Message-ID: <1142559980.525680.282250@u72g2000cwu.googlegroups.com> Is this Haskell implementation what you want? It does the wildcard matching through a state machine and it essentially threads the state machine through the cartesian product, switching to the ordinary cartesian product when possible as an optimisation. The execution of the state machine is shared by strings with the same prefix making it reasonably efficient even though the state machine itself isn't optimised. If it doesn't work, I'm sure it's only a few typos away... -- generate strings of length n from alphabet l such that -- the state machine, with transition function t, is not on -- a final state (determined by function f) at the -- end of the string. -- If the state is ever 'unmatchable' (as determined by u) -- we just return the cartesian product as no rejection -- can take place. generate f u t s 0 l = if f s then [] else [[]] generate f u t s n l | u s = sequence (replicate n l) | otherwise = [a:b | a <- l, let s' = t s a, b <- generate f u t s' (n-1) l] -- The states are lists of regular expressions -- where [a,b,..] means match a or b or... -- This is the transition function for our machine. transition pat a = pat >>= d a where -- Brzozowski derivative d a [] = [] d a p@('*':pat) = p:d a pat d a (p:pat) | a==p = [pat] | otherwise = [] -- A terminal state is one that matches the null string terminal p = or $ map terminal' p where terminal' "" = True terminal' ('*':p) = terminal' p terminal' _ = False run n alphabet pat = generate terminal null transition [pat] n alphabet test = run 3 "abc" "aa*a" From just at xs4all.nl Wed Mar 1 12:32:06 2006 From: just at xs4all.nl (Just) Date: Wed, 01 Mar 2006 18:32:06 +0100 Subject: Cross compile generation of .pyc from .py files... References: <1141176107.234667.93210@e56g2000cwe.googlegroups.com> <1141234081.046271.326160@i39g2000cwa.googlegroups.com> Message-ID: In article <1141234081.046271.326160 at i39g2000cwa.googlegroups.com>, venkatbo at yahoo.com wrote: > Terry Reedy wrote: > > ... > > I am under the impression that .pyc files are system independent. > > Have you tried simply copying them over? > > > > tjr > > Hi Terry, > > It appears that python on the target ppc system is expecting to see > ppc-related info in the .pyc files. There is no such thing. > These .pyc were generated at cross > compile time (on i686 system) and packaged, deployed, installed on the > ppc system. The "...has bad magic..." appears to indicate that > ppc-version of python is expecting to see ppc-specific .pyc files, but > is encountering i686-specific .pyc files... For some reason, the > cross-compile step that results in the .pyc files is not generating > them for the proper ppc-target, but is building them for the i686 > system where they were being cross-compiled... .pyc files are only compatible with the same major Python version, so it sounds like you're using different versions on both platforms. Just From aleaxit at yahoo.com Wed Mar 15 11:04:36 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 15 Mar 2006 08:04:36 -0800 Subject: global, globals(), _global ? References: Message-ID: <1hc8e79.imz7zd16x7t3sN%aleaxit@yahoo.com> robert wrote: > Using global variables in Python often raises chaos. Other languages use > a clear prefix for globals. Ruby does ($ means global), but, what other languages? Perl, C, C++, Java (taking a class's statics as Java's equivalent of other languages' globals), etc, etc, all use the same lexical form for identifiers whether local or global, disambiguating in other ways, not by "a clear prefix" ('my' in Perl to declare locals, sort of like 'global' in Python to declare globals, just with the default the other way 'round, etc). Can you please explain what you mean here? Anyway, I'd LOVE expunging the hated 'global' in favour of an explicit namespace (and another one for "free variables in containing functions" for closures), but while this gets often proposed in python-dev, Guido is apparently never going to approve such a change (even in Py3k where backwards compatibility could be broken), so I've given up on it. Alex From johnpote at blueyonder.co.uk Thu Mar 16 11:27:27 2006 From: johnpote at blueyonder.co.uk (John Pote) Date: Thu, 16 Mar 2006 16:27:27 GMT Subject: python2.4.2 + win95, import socket dll error References: <8V2Sf.151134$Q22.119606@fe1.news.blueyonder.co.uk> Message-ID: Dennis, Thanks for the info. Found winsock2.0 on the MS knowledge base site. Downloaded, installed (with the y2k upgrade as recommended) and, amazingly, all is working. My simple socket server works no problem as does a test http client sending data to my web site. This latter program seems a little grainy on updating the wxPython GUI compared to my modern XP box and slightly older W2K laptop. But its working! You might like to know: I tried searching for winsock 2.2, on MSK base no hits on google search many hits but the ones I could make out all refered to winsock2.2.exe as a variant of the spybot worm. Thanks for helping solve the problem, All the best John Pote "Dennis Lee Bieber" wrote in message news:tf0i12t8gtfv3bpjc31omro2k4dlh4mkvh at 4ax.com... > On Thu, 16 Mar 2006 01:09:24 GMT, "John Pote" > declaimed the following in comp.lang.python: > >> Hi all, >> Can someone throw some light on this problem? (is trying to run Python >> 2.4.2 >> on an old win95 box a reasonable thing to do?) >> > Wasn't Winsock updated between W95 and W98? > > You may have the older winsock 1.1, and all the newer stuff is built > against (and trying to load) winsock 2.2 > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < From prettyboy988-google at yahoo.com Fri Mar 10 16:49:49 2006 From: prettyboy988-google at yahoo.com (P Boy) Date: 10 Mar 2006 13:49:49 -0800 Subject: Python and C In-Reply-To: <1142001002.398147.199140@j52g2000cwj.googlegroups.com> References: <1142001002.398147.199140@j52g2000cwj.googlegroups.com> Message-ID: <1142027389.733332.49880@j33g2000cwa.googlegroups.com> I have written some C extension before but it was pretty tedious. I have recently found another approach by using ctypes (http://starship.python.net/crew/theller/ctypes/). Which you develop your C module in dynamic library (DLL in Windows world), the from Python, you can call the C functions in the DLL using ctypes. I have a library from Microsoft, ewfapi.dll, ewfapi.lib (not required), and ewfapi.h (see download) which I want to program the EWF capability in Windows XP Embedded. I was thinking about writing a Python C extension for it, but using ctypes is much easier. I only need to redefine some data structures from the header file, and not worry about common C tasks such as memory management, reference counting, etc. Ewfapi files can be downloaded from http://www.microsoft.com/downloads/details.aspx?FamilyID=eb3b3d35-ae95-4864-ba3c-d488d3980972&displaylang=en I have some sample usage in Python shown below, which I can interactively control the EWF feature using Python shell (in an XP embedded machine). # ewf.py import ctypes import string # These are the functions from the EWF API ##EwfMgrGetDriveLetterFromVolumeName(volumeName) ## ##EwfMgrVolumeNameListIsEmpty(volumeEntry) ## ##EwfMgrVolumeNameEntryPop(volumeEntry) ## ##EwfMgrVolumeNameListDelete ## ##EwfMgrOpenProtected ## ##EwfMgrClose = _ewfapiPy.EwfMgrClose ## ##EwfMgrClearCommand = _ewfapiPy.EwfMgrClearCommand ## ##EwfMgrSetPersistentData = _ewfapiPy.EwfMgrSetPersistentData ## ##EwfMgrGetPersistentData = _ewfapiPy.EwfMgrGetPersistentData ## ##EwfMgrCheckpoint = _ewfapiPy.EwfMgrCheckpoint ## ##EwfMgrRestore = _ewfapiPy.EwfMgrRestore ## ##EwfMgrDisable = _ewfapiPy.EwfMgrDisable ## ##EwfMgrEnable = _ewfapiPy.EwfMgrEnable ## ##EwfMgrCommit = _ewfapiPy.EwfMgrCommit ## ##EwfMgrCommitAndDisableLive = _ewfapiPy.EwfMgrCommitAndDisableLive ## ##EwfMgrCommitFile = _ewfapiPy.EwfMgrCommitFile ## ##EwfMgrSetLevel = _ewfapiPy.EwfMgrSetLevel ## ##EwfMgrGetProtectedVolumeConfig = _ewfapiPy.EwfMgrGetProtectedVolumeConfig ## ##EwfMgrGetProtectedVolumeList = _ewfapiPy.EwfMgrGetProtectedVolumeList ## ##EwfMgrOpenOverlayStore = _ewfapiPy.EwfMgrOpenOverlayStore ## ##EwfMgrGetOverlayStoreConfig = _ewfapiPy.EwfMgrGetOverlayStoreConfig ## ##EwfMgrRegisterLowSpaceNotification = _ewfapiPy.EwfMgrRegisterLowSpaceNotification # Short handle to the API ewfapi = ctypes.windll.ewfapi # Data structure from EWFAPI.h translated into Python # Map these enumerations to string EWF_CMD = { 0 : 'NO Command', 1 : 'Enable', 2 : 'Disable', 3 : 'Set Level', 4 : 'Commit', } EWF_STATE = { 0 : 'Enabled', 1 : 'Disabled', } EWF_TYPE = { 0 : 'Disk', 1 : 'RAM', 2 : 'RAM Reg', } # Forward Declaration pVolumeNameEntry = ctypes.POINTER('VolumeNameEntry') # Structure of a linked-list class VolumeNameEntry(ctypes.Structure): _fields_ = [('Next', ctypes.POINTER(pVolumeNameEntry)), ('Name', ctypes.c_wchar * 256), ] # Set the pointer to the structure ctypes.SetPointerType(pVolumeNameEntry, VolumeNameEntry) # Volume descriptor class VolumeDesc(ctypes.Structure): _fields_ = [('DeviceName', ctypes.c_wchar * 256), ('VolumeID', ctypes.c_ubyte * 16), ] pVolumeDesc = ctypes.POINTER(VolumeDesc) # Overlay configuration class OverlayStoreConfig(ctypes.Structure): _fields_ = [('FormatVersion', ctypes.c_ulong), ('VolumeSize', ctypes.c_longlong), ('NumSegments', ctypes.c_ulong), ('FreeSegments', ctypes.c_ulong), ('SegmentSize', ctypes.c_ulong), ('MaxVolumes', ctypes.c_ulong), ('NumVolumes', ctypes.c_ulong), ('MaxLevels', ctypes.c_ushort), ('VolumeDescArray', pVolumeDesc), ] pOverlayStoreConfig = ctypes.POINTER(OverlayStoreConfig) class Command(ctypes.Structure): _fields_ = [('Command', ctypes.c_int), ('Param1', ctypes.c_ulong), ('Param2', ctypes.c_ulong), ] pCommand = ctypes.POINTER(Command) class FileTime(ctypes.Structure): _fields_ = [('LowDateTime', ctypes.c_ulong), ('HighDateTime', ctypes.c_ulong), ] pFileTime = ctypes.POINTER(FileTime) class LevelDesc(ctypes.Structure): _fields_ = [('LevelName', ctypes.c_wchar * 64), ('LevelEndTime', FileTime), ('LevelDataSize', ctypes.c_longlong), ] pLevelDesc = ctypes.POINTER(LevelDesc) class VolumeConfig(ctypes.Structure): _fields_ = [('Type', ctypes.c_int), ('State', ctypes.c_int), ('BootCommand', Command), ('PersistentData', ctypes.c_ubyte * 32), ('MaxLevels', ctypes.c_ushort), ('ClumpSize', ctypes.c_ulong), ('CurrentLevel', ctypes.c_ushort), ('DiskMap_RamDataSize', ctypes.c_longlong), ('DiskDataSize', ctypes.c_longlong), ('MemMapSize', ctypes.c_ulong), ('VolumeDesc', VolumeDesc), ('LevelDescArray', pLevelDesc), ] def formatUnsigned(u): return '%02X' % u def unsignedArrayToHex(array): return string.join(map(formatUnsigned, array)).replace(' ','') def displayVolumeConfiguration(config, drive): config_type = EWF_TYPE[config.Type] print 'Type : %s' % config_type print 'State : %s' % EWF_STATE[config.State] print 'Boot Cmd : %s' % EWF_CMD[config.BootCommand.Command] print 'Param 1 : %u' % config.BootCommand.Param1 print 'Param 2 : %u' % config.BootCommand.Param2 print 'Persistent Data: %s' % unsignedArrayToHex(config.PersistentData) print print 'Maximum Levels : %u' % config.MaxLevels print 'Clump Size : %u Bytes' % config.ClumpSize print 'Current Level : %u' % config.CurrentLevel if config_type == 'Disk': print 'Disk Map Size : %u Bytes' % config.DiskMap_RamDataSize print 'Disk Data Size : %u Bytes' % config.DiskDataSize else: print 'RAM Data Size : %u Bytes' % config.DiskMap_RamDataSize print 'Memory Map Size : %u Bytes' % config.MemMapSize print 'Device Name : %s' % config.VolumeDesc.DeviceName print 'Volume ID : %s' % unsignedArrayToHex(config.VolumeDesc.VolumeID) print 'Drive : %s' % drive def information(): # Get the pointer and convert to linked-list node volume_list = VolumeNameEntry.from_address(ewfapi.EwfMgrGetProtectedVolumeList()) while 1: drive = chr(ewfapi.EwfMgrGetDriveLetterFromVolumeName(volume_list.Name)) print '%s: = %s' % (drive, volume_list.Name) handle = ewfapi.EwfMgrOpenProtected(volume_list.Name) config = VolumeConfig.from_address(ewfapi.EwfMgrGetProtectedVolumeConfig(handle)) displayVolumeConfiguration(config, drive) if ewfapi.EwfMgrVolumeNameListIsEmpty(ctypes.c_void_p.from_address(ctypes.addressof(volume_list))): break if __name__ == "__main__ ": print 'Running' information() From scott.daniels at acm.org Sat Mar 18 22:40:28 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 18 Mar 2006 19:40:28 -0800 Subject: POP3 Mail Download In-Reply-To: References: <7g1p12ttfcf1sd5v9rrggr6ioushs2e1id@4ax.com> Message-ID: <441cd069@nntp0.pdx.net> Bob Piton wrote: > I think what he is hinting at is that you are missing a right parentheses. > > msgNum = int(split(msg, " ")[0] > should be: > msgNum = int(split(msg, " "))[0] Or more likely: msgNum = int(split(msg, " ")[0]) > msgSize = int(split(msg, " ")[1] > should be: > msgSize = int(split(msg, " "))[1] Similarly: msgSize = int(split(msg, " ")[0]) More readably: msgNum, msgSize = [int(text) for text in split(msg, " ")[:2]] > Now if only somebody would tell me, with elementary examples, how you > write to the thing called 'stdout' and how you read from 'stdin'. import sys print 'parrot' # writes to sys.stdout print >>None, 'limburger' # Also writes to sys.stdout print >>sys.stdout, 'roquefort' # Also writes to sys.stdout sys.stdout.write('Shropshire -- the cheese of the gods\n) # Also oneline = raw_input('prompt: ') # reads from sys.stdin for line in sys.stdin: # reads line from sys.stdin print 'The current line is: %r' % line if not line.strip(): break chunk = sys.stdin.read(23) # reads a series of bytes from sys.stdin Warning: idle does not implement line iteration as in the for loop. Also the read in both line iteration and .read(N) may well read the input in "block mode", so you may have to type-ahead or end with an end-of-file (^D for Unix, ^Z for Windows) before it starts processing the lines. --Scott David Daniels scott.daniels at acm.org From fakeaddress at nowhere.org Mon Mar 6 12:11:46 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 06 Mar 2006 17:11:46 GMT Subject: spliting on ":" In-Reply-To: References: <1141491273.776287.66070@j33g2000cwa.googlegroups.com> Message-ID: Peter Hansen wrote: > The archives could tell you more, but basically on is usually interested > in *identity* with a singleton object (None), not in whether the object > on is examining happens to compare equal. A custom object could be > designed to compare equal to None in certain cases, even though it *is > not* None, leading to the "== None" approach being defective code. But if a custom class allows instances to compare as equal to None, we might reasonably expect the programmers had a reason. There's not much anyone can do with None besides passing it around and comparing it by value or identity. Insisting on 'is' rather than '==' will break whatever polymorphism such a custom object was trying to achieve. > In the specific code in question, it won't make any differences, but I > pointed it out to help folks who don't know this to start developing the > safer habit, which is always to use "is" and "is not" with None (or, > generally, with other singletons). Hmmm... To make my code safer, I'm thinking I should replace doc strings that say "if bluf is Null" with "if blurf compares equal to Null". -- --Bryan From nun at example.com Sun Mar 26 13:34:28 2006 From: nun at example.com (Mitja Trampus) Date: Sun, 26 Mar 2006 20:34:28 +0200 Subject: maximum() efficency In-Reply-To: References: Message-ID: Steve R. Hastings wrote: > I was looking at a Python function to find the maximum from a list. > The original was more complicated; I simplified it. The built-in max() > function can replace the simplified example, but not the original. But you forgot to shuw us the original... [snip several implementations] > Of course, it's a little ugly to use a[0] instead of "maxval". And I'm > trying not to index a list, and here I am indexing another list. So: > > def maximum(lst): > for v in lst: > try: > if maxval > v: > maxval = v > except NameError: > maxval = v > return maxval > > In my testing on my computer, the above function works perfectly. Even > if you do this: > >>>> maxval = 100 >>>> print maximum(cmp, [2, 0, 3, 1]) > 3 > > In other words, you get a NameError in the function even if there is a > global variable with that name. That's with Python 2.4, however... is > this function guaranteed to work in all Python versions? Not 100% sure, but I think yes. People with longer experience in python can answer definitely. Or you can try it out yourself. The reason it works is that this: def f(): print a a=7; f() works and prints 7 (global a is used), while this def f(): print a a = 12 a=7; f() does NOT work. Python notices that a is going to get assigned to inside f and treats it as a local variable. This is also the case with your code. Try out the above examples without a=7 and notice the different error messages... > The clear winner was the iterator version. It was much faster than the > others, and in my opinion it is simpler and easier to understand than any > of the others. I would have done it in the same way, but probably without the iterators. I.e., like this: def maximum(lst): try: m = lst[0] except (TypeError, IndexError): raise Exception "Non-sequence or empty sequence given to maximum") # (you forgot the above sanity checks in your code. # not strictly necessary, but nice to have.) for x in lst: if x>m: m=x return m From http Wed Mar 15 19:19:06 2006 From: http (Paul Rubin) Date: 15 Mar 2006 16:19:06 -0800 Subject: "pow" (power) function References: <1142465999.800332.73050@i39g2000cwa.googlegroups.com> Message-ID: <7xr753qm11.fsf@ruckus.brouhaha.com> Sch?le Daniel writes: > >>> timeit.Timer("111**0.3").timeit() > 2.3824679851531982 > >>> timeit.Timer("pow(111,0.3)").timeit() > 4.2945041656494141 > > interesting result > seems that ** computates faster Maybe "111**0.3" parses faster than pow(111,0.3), if timeit uses eval. Also, pow() may incur more subroutine call overhead--better check the bytecode for both versions. From hancock at anansispaceworks.com Thu Mar 9 19:22:32 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 9 Mar 2006 18:22:32 -0600 Subject: Python Evangelism In-Reply-To: References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> Message-ID: <20060309182232.6349808c@samwise.anansi> On Thu, 09 Mar 2006 20:21:59 +0100 Magnus Lycka wrote: > It's not too late to rename the cheese shop though. > (We don't need even more stink...) I love cheese, so no problem on that score. But the problem is, if you actually know where "Python" comes from, you are likely to suspect that said site contains no cheese. I think even GvR mentioned this at PyCon. ;-) OTOH, I guess ironic naming can be cool, too. I'm still a little put off by "Dogpile" though. And isn't there a language called "brainfuck" or something? So "python" is hardly the worst. Reminds me of Slartibartfast's original name in the Hitchhiker's radio scripts -- the point being that he has this really embarrassing name and doesn't want to talk about it. The original joke was funnier (but unbroadcastable). Even now I'm wondering if some filter is going to kill this message. Anyway, "python" could theoretically apply the "bad=good" marketing, although something venomous would probably be more effective. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From lycka at carmen.se Wed Mar 1 05:57:59 2006 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 01 Mar 2006 11:57:59 +0100 Subject: time.sleep(1) sometimes runs for 200 seconds under windows In-Reply-To: References: <*firstname*nlsnews-46208F.13454626022006@news.verizon.net> Message-ID: Mladen Adamovic wrote: > Magnus Lycka wrote: > >> On Windows that it. At least on Linux and Solaris, time.clock() returns >> CPU time. If time.clock() returns significantly different values before >> and after time.sleep(1), there's something seriously broken in sleep on >> such platforms. > > No! It seems I can't say anything in this thread without getting contradicted! :) I'm sorry if I wasn't clear in explaining the concept of CPU time in Unix (and other multi user operating systems). This is an entity that is registered per process. Roughly, the code below means that calling f(arg) used s CPU seconds *in* *this* *process*. c0 = time.clock() f(arg) s = time.clock() - c0 If f is time.sleep, s should be 0, or at least very close to 0 on systems such as Linux where time.clock() measures CPU time. Otherwise something is broken. (On Linux, where CPU time has a low resolution (100 ms?) I've never seen any other figure than 0.0.) There will obviously be other processes using the CPU while this process is sleeping, but this process should use no CPU time. Wall time delays will obviously depend on the load of the machines in question. I rarely see > 1 ms on Linux boxes with a low load. With a higher load, or many users, I see delays of up to 10 ms or so now and then, but rarely more. I suspect that observations from Java might not be completely relevant for Python. I suspect the Java implementation might add additional delays. From tjreedy at udel.edu Fri Mar 17 00:35:52 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 17 Mar 2006 00:35:52 -0500 Subject: Threads modify "global" variable -- asking for trouble? References: <1142567916.313302.109920@i39g2000cwa.googlegroups.com> <1142568360.823100.3460@i40g2000cwc.googlegroups.com> Message-ID: "J Rice" wrote in message news:1142568360.823100.3460 at i40g2000cwc.googlegroups.com... > > My apologizes, I missed the newish FAQ entry on this. The addrbl() > method looks like this: > > def addRBL(self, testname, result, info=""): > self.testresultsRBL[testname] = result, info > > So according to the FAQ, D[x] = y, where D is a dictionary, is atomic > and therefore thread-safe. Right? I believe an alternative, mentioned elsewhere by Tim Peters, is for workers to send results (here (testname,result,info) ) back in a results queue read by the main thread. tjr tjr From nessus at mit.edu Tue Mar 21 16:24:23 2006 From: nessus at mit.edu (Douglas Alan) Date: Tue, 21 Mar 2006 16:24:23 -0500 Subject: Spam avoidance Message-ID: I've noticed that there is little to no spam in comp.lang.python and am wondering how this is accomplished. Is there a moderator who actively cancels spam? If so, that wouldn't seem to prevent spam from making it through to the mailing list version of the newsgroup. Is there an exceptionally good spam filter in place? If so, I haven't previously seen one that works so well. Have spammers just given up on Usenet, figuring that there are more exciting places to spam than the Big 8 dinosaur? The reason that I ask is that I help to run another newsgroup (rec.music.gaffa) and we avoid spam by requiring that every participant who wants to post has to register on a Mailman. But I think that this approach has the seriously detrimental effect of discouraging new participants, so I've been wondering about alternative approaches. |>oug From kveretennicov at gmail.com Mon Mar 6 14:18:46 2006 From: kveretennicov at gmail.com (kveretennicov at gmail.com) Date: 6 Mar 2006 11:18:46 -0800 Subject: Incorrect Decimal-Float behaviour in comparison tests In-Reply-To: References: Message-ID: <1141672726.463234.80400@i40g2000cwc.googlegroups.com> (Please excuse my English) Fredrik Lundh wrote: > is this > > >>> 1.0 > "0" > False > > also a bug ? It may be tolerable for unrelated types like int and list, but it's a gross usability issue when it comes to mixing floats and decimals. I believe the latter are going to be mixed and compared a lot (mostly accidentally). Current decimal/float comparison will be a rich source of obscure bugs. Consider expression "n > 0.1", where n is some "number". This expression works as expected while type(n) in (int, long, float). But when you add Decimal to the list of numeric types, it becomes a bug. Worse, a hidden bug. Now, if decimal/float comparison raised a TypeError, like (decimal + float) does, the bug would surface much earlier. Another option is to coerce decimal and float to the same type, possibly with loss of precision. It could be controlled via decimal context. (This has probably been discussed to death. If so, just point me in the right direction.) - kv From johnjsal at NOSPAMgmail.com Mon Mar 6 21:48:30 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 06 Mar 2006 21:48:30 -0500 Subject: Is this not infinite? In-Reply-To: <440cdf90$1_2@newspeer2.tds.net> References: <440cdf90$1_2@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > This should be > def __init__(self, etc....): > Base.__init__(self, etc...) > It's a typo in the book. > Thank goodness! At least I know my mind is heading in the right direction then... :) From cito at online.de Fri Mar 24 16:06:30 2006 From: cito at online.de (Christoph Zwerschke) Date: Fri, 24 Mar 2006 22:06:30 +0100 Subject: Multiplying sequences with floats In-Reply-To: References: Message-ID: Andrew Koenig wrote: > Christoph Zwerschke wrote: > >> Anyway this would be an argument only against the variant of typecasting a >> float with a fractional part. But what about the other variant which >> raises an error if there is a fractional part, but works if the float is >> actually an exact integer, like the result of 4.0//2. > > I think that's a really bad idea, because of the possibility that the result > might happen to be an exact integer on one implementation but not another. > In such situations, the fact that it might fail on implementation X may well > be impossible to detect by any amount of testing on implementation Y. Such > untestable errors are such a nuisance that it would better for the language > to encourage programmers to give them a wide berth. 1./20*40 == 2 or math.sqrt(4.0) == 2 may not always be True (on my platform it is True), but on every platform 4.0//2 == 2 should be True. More general, the result of a//b should always be an exact integer, and a//b == int(a/b) for all positive numbers a,b, no matter on which platform. If not, I would consider a//b broken on that platform. And if a//b == int(a/b) is True, I think it is also reasonable to expect that a//b * list is the same as int(a/b) * list -- Christoph From frank at chagford.com Tue Mar 14 04:32:39 2006 From: frank at chagford.com (Frank Millman) Date: 14 Mar 2006 01:32:39 -0800 Subject: SSL/TLS - am I doing it right? In-Reply-To: References: <1142240607.501914.4390@j52g2000cwj.googlegroups.com> <1142247180.180132.256110@v46g2000cwv.googlegroups.com> <1142252828.097230.36540@e56g2000cwe.googlegroups.com> Message-ID: <1142328759.640029.202910@j52g2000cwj.googlegroups.com> Sybren Stuvel wrote: > Frank Millman enlightened us with: > > If I understand correctly, a 'man-in-the-middle' attack would > > involve someone setting up a 'pseudo server', which gives the > > correct responses to the client's attempt to log in > > That's right. Usually it's done by proxying the data between the > client and the real server. > > > and would also involve someone manipulating the client parameter so > > that it points to the pseudo server instead of the real server. > > Yup. This can be done in various ways, like ARP poisoning of the > network. Then the IP address will not change, but the network card > that the traffic is sent to will. The fraudulent server, having the > correct ARP table, can then forward the captured data to the real > server. > > > What I have not understood is how to prevent this. How can the > > client distinguish between a valid server and a fraudulent one? > > By checking the certificates. The CA mustn't sign server certificates > except for the real server. The fraudulent server thus has no valid > server certificate. > I don't know how to check the certificates. None of the documentation I have read spells out in detail how to do this. What about this idea? I am not looking for a state-of-the-art solution. I am looking for something that is 'good enough' for a typical SME with its own internal network. Assume that the server is reasonably protected, i.e. can only be accessed by administrators with valid permissions. Assume that the client is reasonably protected - i.e. a fraudster cannot access/change the file system. If this cannot be assumed, all bets are off, as the fraudster can replace the pointer to the client software with one to a modified version that bypasses the authentication procedure, and we are back to square one. Using openssl, generate a key for the server, generate a self-signed certificate, and extract the sha1 fingerprint of the certificate. The key must be kept secure but the fingerprint can be published. When a client wishes to connect to the server, it must read a parameter which includes the ip address, the port number, and the fingerprint. After establishing an SSL connection, the client compares the session fingerprint (TLSLite has a getFingerprint() function) with the parameter. If different, client assumes it is talking to an imposter and disconnects. Are there any gaping holes in this approach? Thanks Frank From mahs at telcopartners.com Sat Mar 11 17:27:05 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Sat, 11 Mar 2006 14:27:05 -0800 Subject: Dictionary project In-Reply-To: <00ad01c64553$93d01e90$6400a8c0@D1FWTS61> References: <00ad01c64553$93d01e90$6400a8c0@D1FWTS61> Message-ID: brandon.mcginty at gmail.com wrote: > Hi All, > First, I hope this post isn't against list rules; if so, I'll take note in > the future. > > I'm working on a project for school (it's not homework; just for fun). > For it, I need to make a list of words, starting with 1 character in length, > up to 15 or so. > It would look like: > > A B C d E F G ... Z Aa Ab Ac Ad Ae Aaa Aab Aac > > Etcetera. > > I've looked on Google, and on the python lists at python.org, and haven't > found any code that I can adapt. > I've also tried to adapt some code from Perl, but not knowing the language > very well, I wasn't very successful. > If there is adaptable code on the internet that I've missed, please let me > know, and I'll go on my marry way in search of it. > > Any help would be appreciated. > > Thanks Much, > Brandon McGinty > Brandon.mcginty at gmail.com > Something to adapt: alphabet = "abcd" def allwords(maxlength = 4): def wordgen(outer): for partial in outer: yield partial for letter in alphabet: yield partial+letter gen = alphabet for length in range(maxlength-1): gen = wordgen(gen) return gen >>> list(allwords()) ['a', 'aa', 'ab', 'ac', 'ad', 'aa', 'aaa', 'aab', 'aac', 'aad', 'ab', 'aba', 'abb', 'abc', 'abd', 'ac', 'aca', 'acb', 'acc', 'acd', 'ad', 'ada', 'adb', 'adc', 'add', 'aa', 'aaa', 'aab', 'aac', 'aad', 'aaa', 'aaaa', 'aaab', 'aaac', 'aaad', 'aab', 'aaba', 'aabb', 'aabc', 'aabd', 'aac', 'aaca', 'aacb', 'aacc', 'aacd', 'aad', 'aada', 'aadb', 'aadc', 'aadd', 'ab', 'aba', 'abb', 'abc', 'abd', 'aba', 'abaa', 'abab', 'abac', 'abad', 'abb', 'abba', 'abbb', 'abbc', 'abbd', 'abc', 'abca', 'abcb', 'abcc', 'abcd', 'abd', 'abda', 'abdb', 'abdc', ... 'dcdc', 'dcdd', 'dd', 'dda', 'ddb', 'ddc', 'ddd', 'dda', 'ddaa', 'ddab', 'ddac', 'ddad', 'ddb', 'ddba', 'ddbb', 'ddbc', 'ddbd', 'ddc', 'ddca', 'ddcb', 'ddcc', 'ddcd', 'ddd', 'ddda', 'dddb', 'dddc', 'dddd'] If you want the list sorted by length, as in your example: >>> sorted(_, key=len) ['a', 'b', 'c', 'd', 'aa', 'ab', 'ac', 'ad', 'aa', 'ab', 'ac', 'ad', 'aa', 'ab', 'ac', 'ad', 'ba', 'bb', 'bc', 'bd', 'ba', 'bb', 'bc', 'bd', 'ba', 'bb', 'bc', 'bd', 'ca', 'cb', 'cc', 'cd', 'ca', 'cb', 'cc', 'cd', 'ca', 'cb', 'cc', 'cd', 'da', 'db', 'dc', 'dd', 'da', 'db', 'dc', 'dd', 'da', 'db', 'dc', 'dd', 'aaa', 'aab', 'aac', 'aad', 'aba', 'abb', 'abc', 'abd', 'aca', 'acb', 'acc', 'acd', 'ada', 'adb', 'adc', 'add', 'aaa', 'aab', 'aac', 'aad', 'aaa', 'aab', 'aac', 'aad', 'aba', 'abb', 'abc', 'abd', 'aba', 'abb', 'abc', 'abd', 'aca', HTH Michael From lists at elehack.net Tue Mar 14 08:15:44 2006 From: lists at elehack.net (Michael Ekstrand) Date: Tue, 14 Mar 2006 07:15:44 -0600 Subject: SSL/TLS - am I doing it right? In-Reply-To: <1142338358.686906.226240@p10g2000cwp.googlegroups.com> References: <1142240607.501914.4390@j52g2000cwj.googlegroups.com> <1142247180.180132.256110@v46g2000cwv.googlegroups.com> <1142252828.097230.36540@e56g2000cwe.googlegroups.com> <1142328759.640029.202910@j52g2000cwj.googlegroups.com> <7xy7zdnywx.fsf@ruckus.brouhaha.com> <1142338358.686906.226240@p10g2000cwp.googlegroups.com> Message-ID: <20060314071544.fb92c297.lists@elehack.net> Disclaimer: I am not an expert. Take this with a grain of salt... but I'll throw it out for what it's worth. On 14 Mar 2006 04:12:38 -0800 "Frank Millman" wrote: > > > Using openssl, generate a key for the server, generate a > > > self-signed certificate, and extract the sha1 fingerprint of the > > > certificate. The key must be kept secure but the fingerprint can > > > be published. > > > > Then install a copy of the certificate on the client, that the > > client can authenticate against. > > I wanted to keep the legwork required to set up a new client down to a > minimum. I was hoping that setting a pointer to the client software, > and a pointer to a connection parameter, would be sufficient. If the > fingerprint is an an adequate substitute for the full certificate, I > would prefer it, as it is much smaller, and can easily form part of > the connection parameter. Your client probably installs data files, right? Then just install the server's public key (or a fingerprint thereof) as one of your data files, put a checksum system in place to make sure it isn't tampered with. Or just embed the checksum in your program or a DLL - the server won't be changing its certificate very often. If the user wants to go change the fingerprint to let the program connect to a fradulent server, well, you've got a lot worse problems than SSL will ever help you fix. I suppose a virus could change it, but that'd be a weird (and highly targeted) virus. > > You also want to generate a client > > certificate to install on the server. If there are multiple clients > > you should make a CA rather than trying to keep track of self-signed > > certificates. If you're paranoid, you can scrounge some $20 > > obsolete laptop from ebay and dedicate it to use as a CA, never > > letting it touch the internet (transfer files to and from it on > > floppy disc). > > > > Both you and Sybren are insistent that this is a necessary step, but I > confess I cannot see the need for it. The client is lightweight, and > authenticates itself to the server using a user id and password. What > is the worst that could go wrong? For what it's worth, the Web does not authenticate clients (for the most part anyway). The server is authenticated - its certificate is checked against the root CA list. But clients aren't expected to have their own certificates. I think that the only time you really need the clients to have certificates is when the certificate *is* your authentication (e.g., in OpenVPN). Likewise, SSH does not verify client certificates (unless you're using PKA, but that's different). Since the password is your authentication, I don't see any reason why the client verifying the server's certificate against its "known good" fingerprint, and then providing username/password as its credentials, is any less secure than SSH with password/keyboard-interactive. Sure, maybe not quite as secure as SSH w/ public key auth, but it's good enough for a lot of stuff. - Michael -- mouse, n: a device for pointing at the xterm in which you want to type. -- Fortune From justin.mailinglists at gmail.com Tue Mar 28 01:33:41 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 27 Mar 2006 22:33:41 -0800 Subject: Obtaining the remote ip address References: Message-ID: <1143527621.291155.238080@i40g2000cwc.googlegroups.com> os.environ['REMOTE_ADDR'] os.environ['REMOTE_HOST'] From johnjsal at NOSPAMgmail.com Tue Mar 28 15:32:32 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 28 Mar 2006 20:32:32 GMT Subject: tips for this exercise? In-Reply-To: References: Message-ID: Brian Quinlan wrote: > I would just write the function like this: > > def genNumbers(): > shuffle_nums = numbers[:] # copy the list to preserve the orginal > # order (if it matters) > random.shuffle(shuffle_nums) # shuffle the entire list > return shuffle_nums[:5] # return the first 5 elements Thanks. Interesting idea. I did consider copying it, but does that hurt performance each time the function is called? I know it may not be noticeable, but I don't like the idea of doing unnecessary work like that, if it is in fact unnecessary. From tim at pollenation.net Sun Mar 12 14:09:36 2006 From: tim at pollenation.net (Tim Parkin) Date: Sun, 12 Mar 2006 19:09:36 +0000 Subject: Cheese Shop: some history for the new-comers In-Reply-To: <1142189668.450949.228210@e56g2000cwe.googlegroups.com> References: <44126523$0$1016$afc38c87@news.optusnet.com.au> <44141D59.6050806@pollenation.net> <1142178342.382120.236130@j33g2000cwa.googlegroups.com> <1142189668.450949.228210@e56g2000cwe.googlegroups.com> Message-ID: <441471F0.2010204@pollenation.net> Paul Boddie wrote: > Fredrik Lundh wrote: >>(I'd solve this by adding disambiguation to the page itself, since >>people can arrive on it in many different ways. good information >>design is not only about what's on the front page...) > True, but then I'd hope that, for example, a "Support" link would lead > to a "Support" page which had support-related resources. Any front page > link to a "developers of the implementation" page would also have to > lead to something pertinent to that description, too. But having looked > in the past at various parts of the old site in order to find canonical > resources, perhaps the biggest challenge in maintaining the Python site > is having coherent navigation with less redundant content: I got the > impression that there were a number of pages that had been kept around > "just in case we don't mention this somewhere else" and links through > such pages with no guarantee that you'd get to an up-to-date summary of > the desired information in a timely fashion, if at all. > Indeed, that is one of the big challenges and we're trying to approach it from the top down. At the moment we've trimmed down the number of top level sections and the next stage is to address the top page of each of those sections (e.g. the 'community', 'documentation','python-dev' pages). Still some work left cleaning up after the move to the new site but this is going to be a priority very soon. Do you want me to include you on any emails regarding this? Tim Parkin From PPNTWIMBXFFC at spammotel.com Wed Mar 22 03:57:29 2006 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Wed, 22 Mar 2006 09:57:29 +0100 Subject: From Python to c++ References: Message-ID: Heck! I received 1 useless answer in comp.lang.c++ and here I get useful links/hints and even a code-pattern! Great. Thank you all. Sorry for posting a c++-problem here, but it was derived from my thinking the Python way... Cheers, Marco From spire01 at hotmail.com Sun Mar 26 02:57:55 2006 From: spire01 at hotmail.com (Spire 01) Date: Sun, 26 Mar 2006 07:57:55 +0000 Subject: SSH, remote login, and command output Message-ID: Greetings! I'm working on a Python program for a small LAN of Linux systems running Gentoo, and I need a little help figuring out what I need to do it. So what I'd like to do is, from any given computer, log on to every other computer, run a certain command (which normally outputs text to the terminal), and store the output so I can use the aggregate statistics later in the program. I would normally something along the lines of SSH to do it, but I don't know what I would need to pull that off in Python. There's also one complication: the systems could be Gentoo systems, or they could be logged into Windows since they're dual booted. Considering all of this, can anyone give me some recommendation as to what library I should learn how to use to pull this off? I admit, I haven't done too much in the way of networks, but if someone can tell me what I need to do remote logins in this way, I'll do what I can to make it work. Thanks a million! Spire _________________________________________________________________ Is your PC infected? Get a FREE online computer virus scan from McAfee? Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From deets at nospam.web.de Mon Mar 6 06:58:21 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 06 Mar 2006 12:58:21 +0100 Subject: Suggesting the use of StandardError as base of error Exceptions. In-Reply-To: References: Message-ID: <472metFd4vprU1@uni-berlin.de> Antoon Pardon schrieb: > In a number of cases I have a program that looks like the following. > > for case in all_cases: > try: > treat(case) > except Exception, ErrInfo: > generate_traceback() > > The idea is to get as much information as possible when something > goes wrong but at the same time treat as many cases as possible. > > Then one day things broke. The reason was that in some circumstances > treat would decide that things were beyond control and called sys.exit > However sys.exit doesn't return to the O.S. immediately but raises > SystemExit, which was caugth by the code and the loop continued. > > I then took a look at http://docs.python.org/lib/module-exceptions.html > which describes the exception heirarchy as follows: > > Exception > +-- SystemExit > +-- StopIteration > +-- StandardError > | + > | + All kind of error exceptions > | + > +---Warning > + > + All kind of warnings > + > > and came to the conclusion, that it would be better to write my code > as follows: > > for case in all_cases: > try: > treat(case) > except StandardError, ErrInfo: > generate_traceback() > > Unfortunatly this doesn't work either because a lot of the error > exceptions in the stdlib (if not all) inherit directly from > Exception instead of from StandardError. The documentation also > seems to suggest this use for users exception. > > Now I was wondering if it wouldn't be better that for exception > that indicate some error condition that these would inherit > from StandardError and that this would be indicated in the > documentation and reflected in the stdlib? > > Would it break much code to make this change? My first impression > would be no, but I could be missing something. There has been a discussion on this just a few days ago, have you read that? There is even a PEP mentioned. http://groups.google.com/group/comp.lang.python/browse_thread/thread/56d7c5767a205866/d2403ae0c6267ca1 Diez From eoinrogers at gmail.com Wed Mar 22 16:07:33 2006 From: eoinrogers at gmail.com (Byte) Date: 22 Mar 2006 13:07:33 -0800 Subject: Getting a loop to activate a loop above it Message-ID: <1143061653.100159.127550@u72g2000cwu.googlegroups.com> The following code will not work for me: x = 1 while x == 1: print 'hello' x = input('What is x now?: ') while x == 2: print 'hello again' x == input('What is x now?: ') The second loop dose not seem to be able to activate the loop above it.... Proof from my command line: $ python program-that-dose-not-work.py hello What is x now?: 2 hello again What is x now?: 1 hello again What is x now?: So, now I ask you: how do I make it work? Thanks in advance, -- /usr/bin/byte From sullivanz.pku at gmail.com Tue Mar 7 02:18:09 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 6 Mar 2006 23:18:09 -0800 Subject: Confused by Method(function) of a module and method of aclass/instance In-Reply-To: References: <1141712572.831656.326200@u72g2000cwu.googlegroups.com> Message-ID: <1141715889.606254.139940@i40g2000cwc.googlegroups.com> Yes, I checked out that I have already run "from string import *". So the lower() means string.lower() function. However, something else came out just now: >>>instr='a' >>>instr.join('b') 'b' >>>instr.lower() 'A' >>>instr 'a' Both as the method of the type str, join never use the instr instance object as method parameters while lower do. Compared with the .lower() method, the instr.join() looks like an independent function, which use the parameters in the parenthesis and return a value without instr being changed. So why should it be programmed into the str type? More confusing things came out to me: >>>str().lower() '' #well, this is understandable. >>>str.lower(str(),'A') 'a' How do you explain this result? Sincerely, thank you so much for help. From eswhite at gmail.com Tue Mar 21 16:12:12 2006 From: eswhite at gmail.com (Eric White) Date: Tue, 21 Mar 2006 16:12:12 -0500 Subject: Module import information In-Reply-To: References: <76515c6c0603210549k7576a94j87bde2da463e8f7f@mail.gmail.com> <76515c6c0603210904pedc11a8n2c49fac93e60c7c4@mail.gmail.com> Message-ID: <76515c6c0603211312r31a50f58sfeafb97a11663516@mail.gmail.com> I found a builtin function called "execfile" that seems to suite my needs quite well. The import function is less applicable. Thanks for your time. On 3/21/06, Steve Holden wrote: > > Eric White wrote: > > Peter: > > > > Thanks for the reply. Consider the following situation: > > > > A set of variable names is defined along with a list of possible values > > for each. A second set of variable names is defined along with an > > expression for generating a value for each. For each possible > > permutation of variables from the first set, a python script is created > > that contains commands that initialize the variable set with the > > permuted values. A second python script is created that contains > > commands for connecting to a database and storing the values of the > > second set of variables after running the associated expression for > each. > > > > We would like to be able to use the scripts above to drive a python > > script containing a system of equations specified at run time and to > > store the results. This "master" script contains the following calls: > > > > import somemodule > > > > # do stuff ... > > > > # initialize permuted variables > > somemodule.init() > > > > # do more stuff ... > > > > # store results > > somemodule.save() > > > > # do more stuff ... Etc. > > > > We would like for the call to init to initialize variables in the > > context of the "master" script. To do this inside somemodule we use the > > sys.modules dictionary to find a reference to the master module by name > > and initialize variables at this reference. > > > > What I would like to know if it is arbitrarily possible to "walk" the > > import hierarchy from any point. It is not apparent that python's > > optimization of subsequent imports of the same module is relavent. > > > It seems to me that you could achieve the same end by accessing the > calling stack frame inside the calls to your somemodule.functions(). > Whether this is acceptable or not (and whether you are prepared to put > up with the necessary voodoo) is another question. > > However, this would lead to atrocious coupling in your program. It's the > kind of thing people used to use Fortran common blocks for, for goodness > sake! > > The point Peter was trying to make about the distinction between first > import of a module and subsequent ones is, I suspect, quite relevant, as > you made it appear that you wanted to rely on code executed *during the > import* to distinguish its importer. Clearly this would only be possible > on the first import, as subsequent imports wouldn't execute the module's > code. > > But now it appears that the import structure isn't really as relevant as > the calling relationships anyway, no? > > Or am I misunderstanding your intent? > > regards > Steve > > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd www.holdenweb.com > Love me, love my blog holdenweb.blogspot.com > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From adam.deprince at gmail.com Fri Mar 24 10:05:27 2006 From: adam.deprince at gmail.com (Adam DePrince) Date: 24 Mar 2006 07:05:27 -0800 Subject: Multiplying all the values in a dictionary In-Reply-To: References: <1143162298.28477.7.camel@cornell> <1143165699.692995.3220@e56g2000cwe.googlegroups.com> <1143177799.833144.108400@t31g2000cwb.googlegroups.com> Message-ID: <1143212727.752841.43380@u72g2000cwu.googlegroups.com> Droppings from other timing tests; starbucks was kicking me out and I was in a hurry. Cheers - Adam DePrince From jukka.aho at iki.fi Sun Mar 12 14:56:29 2006 From: jukka.aho at iki.fi (Jukka Aho) Date: Sun, 12 Mar 2006 21:56:29 +0200 Subject: Customizing character set conversions with an error handler Message-ID: When converting Unicode strings to legacy character encodings, it is possible to register a custom error handler that will catch and process all code points that do not have a direct equivalent in the target encoding (as described in PEP 293). The thing to note here is that the error handler itself is required to return the substitutions as Unicode strings - not as the target encoding bytestrings. Some lower-level gadgetry will silently convert these strings to the target encoding. That is, if the substitution _itself_ doesn't contain illegal code points for the target encoding. Which brings us to the point: if my error handler for some reason returns illegal substitutions (from the viewpoint of the target encoding), how can I catch _these_ errors and make things good again? I thought it would work automatically, by calling the error handler as many times as necessary, and letting it work out the situation, but it apparently doesn't. Sample code follows: --- 8< --- #!/usr/bin/python import codecs # ================================================================== # Here's our error handler # ================================================================== def charset_conversion(error): # error.object = The original unicode string we're trying to # process and which has characters for which # there is no mapping in the built-in tables. # # error.start = The index position in which the error # occurred in the string # # (See PEP 293 for more information) # Here's our simple conversion table: table = { u"\u2022": u"\u00b7", # "BULLET" to "MIDDLE DOT" u"\u00b7": u"*" # "MIDDLE DOT" to "ASTERISK" } try: # If we can find the character in our conversion table, # let's make a substitution substitution = table[error.object[error.start]] except KeyError: # Okay, the character wasn't in our substitution table. # There's nothing we can do. Better print out its # unicode codepoint as a hex string instead: substitution = u"[U+%04x]" % ord(error.object[error.start]) # Return the substituted string and let the built-in codec # continue from the next position: return (substitution,error.start+1) # ================================================================== # Register the above-defined error handler with the name 'practical' # ================================================================== codecs.register_error('practical',charset_conversion) # ================================================================== # TEST # ================================================================== if __name__ == "__main__": print # Here's our test string: Three BULLET symbols, a space, # the word "TEST", a space again, and three BULLET symbols # again. test = u"\u2022\u2022\u2022 TEST \u2022\u2022\u2022" # Let's see how we can print out it with our new error # handler - in various encodings. # The following works - it just converts the internal # Unicode representation of the above-defined string # to UTF-8 without ever hitting the custom error handler: print " UTF-8: "+test.encode('utf-8','practical') # The next one works, too - it converts the Unicode # "BULLET" symbols to Latin 1 "MIDDLE DOTs": print "Latin 1: "+test.encode('iso-8859-1','practical') # This works as well - it converts the Unicode "BULLET" # symbols to IBM Codepage 437 "MIDDLE DOTs": print " CP 437: "+test.encode('cp437','practical') # The following doesn't work. It should convert the # Unicode "BULLET" symbols to "ASTERISKS" by calling # the error handler two times - first time substituting # the BULLET with the MIDDLE DOT, then finding out # that that doesn't work for ASCII either, and falling # back to a yet simpler form (by calling the error # handler again, which will this time substitute the # MIDDLE DOT with the ASTERISK) - but apparently it # doesn't work that way. We'll get a # UnicodeEncodeError instead. print " ASCII: "+test.encode('ascii','practical') # So the question becomes: how can I make this work # in a graceful manner? --- 8< --- -- znark From irmen.NOSPAM at xs4all.nl Wed Mar 22 17:40:10 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 22 Mar 2006 23:40:10 +0100 Subject: Uploading files from IE In-Reply-To: References: Message-ID: <4421d24a$0$11071$e4fe514c@news.xs4all.nl> AB wrote: > All right... I already hated IE. But, now I do even more. My scripts > upload function is working in Firefox, but not in IE. If I upload a file > from Internet Explorer I get a file on the system named for the full path > from the users computer... > > example... > They user uploads C:\mydocs\test.jpg > it ends up at /path/to/webdir/C:\mydocs\test.jpg > instead of /path/to/webdir/test.jpg try something like this: filename = os.path.basename(fullpathname) --Irmen From lycka at carmen.se Fri Mar 3 12:41:35 2006 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 03 Mar 2006 18:41:35 +0100 Subject: white space in expressions and argument lists In-Reply-To: References: <44074fea@nntp0.pdx.net> Message-ID: Sybren Stuvel wrote: > Scott David Daniels enlightened us with: > >>One reason is such code changes too much on code edits, which makes >>code differences hard to read. > > Good point. I'll keep it in mind :) Think particularly about using version management systems and applying patches coming from different sources etc. Touching more lines of code than you actually need will both make it difficult for a reviewer to understand what has changed (although good diff tools can be told to ignore pure whitespace changes) and it will also increase the risk of conflicts in the version management system if several people are editing the same code. Finally, if you end up with something like... a = 1 b = 5 df = 7 ew = 5 qw = 7 a2 = 5 a4 = 7 d3 = 5 df = 7 this_is_a_very_long_variable_name_indeed = 42 ...it's *not* easier to see what the value of e.g. a4 is than if you had just used one space between the variable name and the =. As usual, Guido is right, even if it isn't obvious at first unless you are Dutch. ;^) From paul at boddie.org.uk Wed Mar 8 12:32:48 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 8 Mar 2006 09:32:48 -0800 Subject: Type Hinting vs Type Checking and Preconditions References: <1141826957.934692.289430@i40g2000cwc.googlegroups.com> <1141828474.684065.250070@j33g2000cwa.googlegroups.com> Message-ID: <1141839167.512902.221820@p10g2000cwp.googlegroups.com> Tom Bradford skrev: > Really what we're talking about here is weak typing in the form of Careful with the terminology! Weak typing is something else entirely. > optional type hinting performed on a function by function basis. As an > option, what it would do is allow an author to semantically 'hint' to > the interpreter that a function is expecting a certain type, and > perform any implicit conversion if the passed type is not what was > expected, thus translating to a semantically expected result. But is it adaptation or some weaker form of that concept, where "x : int" just means that you call the "int" function on "x" to coerce it (with an exception raised if that doesn't work), or is it more of a type-checking system, where you call "isinstance(x, int)" and raise an exception if that test returns false? > It is my feeling that this doesn't represent a sea-change in the way > Python does things, and it's certainly *not* the way things are done in > Java or C++, as both of those languages are strongly typed, wherein you > can't even pass a parameter if it isn't of the expected type, or a > subclass thereof. Careful with the terminology, again! That calling a function with the wrong type of argument ultimately leads to a run-time exception is actually a sign that Python also has strong typing - it just doesn't enforce particular argument types when actually calling a function or method (but typically instead when looking up attributes and methods on objects). Certainly, explicit type-checking (the second case above) is different from how Python currently does things (except for a few low-level calls), whereas some form of coercion is not the same as how Python currently behaves, since passing an object of some previously-unknown numeric type into a function which performs multiplication wouldn't result in the conversion of that object into an int or float, for example. > The fact is, that with a system such as this, you could just 'not use > it', and none would be the wiser, as it's an authorship extension > rather than a calling extension. What I was suggesting is that nothing > change other than function/method prototypes, and that everything, > everwhere, at all times continues to be represented as scalars. I don't follow the scalars reference - sounds like Perl terminology to me - but whilst "x : int" might be convenient notation for either type-checking or coercion/adaptation, the problem would soon arise where paranoid developers add such notation to their code in order to insist that only types that they can think of be used with their APIs. The consequence would be arbitrary limits on extensibility - you'd actually have to update code to work with new or previously-unconsidered kinds of objects - and with this, you'd soon be "the wiser" about usage of the feature in question. As C++ has shown, when designing exotic notations to describe types, you end up with a language in itself to do that job; at which point you might arguably be better served by either writing your type declarations in Python rather than starting with an insufficient mini-language which grows into a monster or, as I'd rather like to imagine, employing alternative approaches to deal with program analysis. Paul From mrstephengross at hotmail.com Mon Mar 6 15:13:01 2006 From: mrstephengross at hotmail.com (mrstephengross) Date: 6 Mar 2006 12:13:01 -0800 Subject: Newbie ZSI / syntax question Message-ID: <1141675981.134225.177280@v46g2000cwv.googlegroups.com> I'm getting started working with ZSI. I have a client script that looks like this: =================== import ZSI.client b = ZSI.client.Binding() b.Send('http://...', 'verifyUserRegistered', '00:00:00:00:00:00') =================== When I run it, I get the following error: ======================= File "./sage_installer.py", line 13, in ? b.Send('http://...', 'verifyUserRegistered', '00:00:00:00:00:00') File "/usr/local/lib/python2.3/site-packages/ZSI/client.py", line 209, in Send self.h.connect() File "/usr/local/lib/python2.3/httplib.py", line 548, in connect raise socket.error, msg socket.error: (2, 'No such file or directory') ======================= I'm trying to make sure I'm calling the Binding.Send() function correctly. Does it look right? Note that I've replaced the actual url (to the php server-side script) with '...' in the above example. Thanks in advance, --Steve (mrstephengross at hotmail.com) From fredrik at pythonware.com Wed Mar 8 07:28:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 8 Mar 2006 13:28:44 +0100 Subject: New python.org website References: <20060307223014.19227.qmail@web25715.mail.ukl.yahoo.com> <1141798982.758191.304090@i39g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: >> The new website is to blah. It's so light colored across the whole thing >> that it kind of just melts away in my mind. Maybe giving a little color >> in the menu bar on the right would help. My experience is that white is >> a bad background color when over used. > > I agree. The text is too loud and the colors are too low. Otherwise > Fredrik Lundh reminded me that there are no good PL language home > pages out there at all. This shouldn't excuse a mediocre design but it > softened my annoyance a little. unfortunately, I don't think "but the others are no better" is an acceptable goal for the Python universe I live in... after all, what's the fun with that? From duncan.booth at invalid.invalid Sat Mar 25 15:53:41 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Mar 2006 20:53:41 GMT Subject: a somewhat off-topic question about linux References: <_oedne4wPJ9DPrjZnZ2dnUVZ_tWdnZ2d@rcn.net> Message-ID: John Salerno wrote: > I'm interested in trying out Linux, probably Ubuntu, but I was wondering > which distribution you guys like to use (because it's a pain trying to > decide!) and you guys are smart. If you just want to try out Linux then a very easy way is to use VMWare Player: download it from http://www.vmware.com/products/player/. You can then run almost any Linux you wish directly on your windows system, no need to reboot or anything. Start with Browser Appliance which is a cut-down installation of Ubuntu (but it is configured so that things like the clipboard interact properly with Windows clipboard, and you can share files by sharing folders on windows and connecting to them from Ubuntu). Then you can use the package manager (on the System menu) to install Python and other packages (when it asks for a password use 'vmware' if you are using the default 'vmware' user). You need about 2Gb of free disk space to install and use VMWare and Browser appliance: all of the Linux file system is stored in one file which expands as required up to 9.5Gb maximum (it helps performance if you keep the file defragmented: use contig.exe from www.sysinternals.com). Once you have Vmware installed, as well as Ubuntu, you can also download Linux images for Novell/Suse, RedHat and literally dozens of other versions of Linux and Unix variants, some preconfigured for specific applications try them out and then throw them away. The only limits are your disc space. > > And to keep it Python related, I'll also ask, is there anything special > I need to know about using Python on Linux? Do any things change, or can > it be used just as I use it on Windows? > The main difference is that it is much easier to install packages which are part of the Ubuntu distribution: just run up the package manager, select the ones to install and download and install happen automatically. From duncanm255 at hotmail.com Thu Mar 2 10:10:16 2006 From: duncanm255 at hotmail.com (D) Date: 2 Mar 2006 07:10:16 -0800 Subject: Stopping Windows Service In-Reply-To: <44060E9C.7050607@websafe.com> References: <1141245687.785561.24450@j33g2000cwa.googlegroups.com> <44060E9C.7050607@websafe.com> Message-ID: <1141312216.423546.182450@p10g2000cwp.googlegroups.com> I must be missing something..in my SvcDoRun function, first line is "self.timeout=10000" , followed by my "while 1:" loop which listens for the connection, processes the data, etc. Where should I place the "rc=win32event.." and "if rc" lines? I have a feeling I'm pretty close here.. :) Thanks very much. Doug From krjacks1 at netscape.net Mon Mar 13 02:23:14 2006 From: krjacks1 at netscape.net (Keith Jackson) Date: Mon, 13 Mar 2006 07:23:14 GMT Subject: automatic from module import * expansion Message-ID: Does anybody know of a tool that will take a module as input, look for any wildcard imports, and then identify what symbols in the module come from which wildcard import? It could then expand out the from module import * to from module import foo, bar. It might need to ask the user on this, since they might want the wildcard import for something special, but it would still be *much* nicer then expanding the imports out by hand. Apologies ahead of time if I've missed something obvious. I did spend some quality time with google, and couldn't find anything. cheers, --keith From n.estner at gmx.de Fri Mar 24 06:11:46 2006 From: n.estner at gmx.de (nikie) Date: 24 Mar 2006 03:11:46 -0800 Subject: Linear regression in NumPy In-Reply-To: References: <1142628938.982098.239850@u72g2000cwu.googlegroups.com> <1142631926.353064.206010@p10g2000cwp.googlegroups.com> <1142639157.977175.257900@u72g2000cwu.googlegroups.com> <%PVSf.52$Qm2.24@trndny03> <1142698211.185324.154130@j33g2000cwa.googlegroups.com> <1143110807.307714.320840@u72g2000cwu.googlegroups.com> Message-ID: <1143198706.448457.24920@e56g2000cwe.googlegroups.com> Robert Kern wrote: > Both functions are described in the full book. Were you just looking at the > sample chapter? No, I've got the full PDF by mail a few days ago, "numpybook.pdf", 261 pages (I hope we're talking about the same thing). I entered "linear_least_squares" and "polyfit" in acrobat's "find text" box, but neither one could be found. From kent at kentsjohnson.com Fri Mar 31 12:21:00 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 31 Mar 2006 12:21:00 -0500 Subject: member variables in python In-Reply-To: <1143821291.915307.157060@g10g2000cwb.googlegroups.com> References: <1143819190.360242.314830@z34g2000cwc.googlegroups.com> <442d4b03$1_2@newspeer2.tds.net> <1143821291.915307.157060@g10g2000cwb.googlegroups.com> Message-ID: <442d5fb9_3@newspeer2.tds.net> PyPK wrote: > ok I reason I was going with globals is that i use this variable in > another class something like this along with above > > testflag = 0 > > class AA: > def __init__(...): > > def methos(self,...): > global testflag > testflag = xx > > class BB: > def __init__(...): > > def method2(..): > if testflag: > print "do this" > is there a better way to access this if we go with what you mentioned > in another class .. 1. Tell BB about the AA instance when it is created: class BB: def __init__(self, aa): self.aa = aa def method(self): if self.aa.testflag: 2. Pass the flag to BB.method() directly: def method(self, testflag): if testflag: Kent From webraviteja at gmail.com Wed Mar 8 03:06:15 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 8 Mar 2006 00:06:15 -0800 Subject: sending a text message via webpage button In-Reply-To: <1141794395.277013.245680@e56g2000cwe.googlegroups.com> References: <1141794395.277013.245680@e56g2000cwe.googlegroups.com> Message-ID: <1141805175.105696.302410@e56g2000cwe.googlegroups.com> http://wwwsearch.sourceforge.net/ClientForm/ From fredrik at pythonware.com Thu Mar 9 15:16:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 9 Mar 2006 21:16:12 +0100 Subject: Python Evangelism References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> Message-ID: Magnus Lycka wrote: > That doesn't make Python easier to sell here... verkligen? jag kan inte p?minna mig om att n?gon n?gonsin langat upp det argumentet, annat ?n m?jligen som ett tamt sk?mt... (borde du inte vara ute p? stan och svira, f?rresten, ist?llet f?r att sitta p? jobbet s? h?r sent? ;-) From gongcheng_g at hotmail.com Mon Mar 27 09:52:18 2006 From: gongcheng_g at hotmail.com (ChengGong) Date: 27 Mar 2006 06:52:18 -0800 Subject: DELETE an image Message-ID: <1143471138.347309.87400@v46g2000cwv.googlegroups.com> hi guys, could u tell me how to delete images ( files) from a folder by using tags in zope? Because I upload images there and test whether it is meet size requirment and then upload it to the folder it supposed to be. Pls help me, thanks. Cheng From finite.automaton at gmail.com Mon Mar 20 17:34:37 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 20 Mar 2006 14:34:37 -0800 Subject: user-supplied locals dict for function execution? In-Reply-To: <441f29ec$0$31422$626a54ce@news.free.fr> References: <1142875454.906993.126370@v46g2000cwv.googlegroups.com> <441eedbd$0$20865$636a55ce@news.free.fr> <1142879594.924929.96440@v46g2000cwv.googlegroups.com> <441f0623$0$23127$626a54ce@news.free.fr> <1142887575.402624.156050@e56g2000cwe.googlegroups.com> <441f29ec$0$31422$626a54ce@news.free.fr> Message-ID: <1142894077.918388.267480@i39g2000cwa.googlegroups.com> > Beautiful is better than ugly. > Explicit is better than implicit. >> Err... I see no contradiction nor conflict here. What to do when explicit is ugly and implicit is beautiful? Aye, there's the rub. ;-) From peter at engcorp.com Wed Mar 8 22:06:17 2006 From: peter at engcorp.com (Peter Hansen) Date: Wed, 08 Mar 2006 22:06:17 -0500 Subject: Send email notification In-Reply-To: References: <1141759889.952367.59260@j33g2000cwa.googlegroups.com> <1141760916.715817.3800@i40g2000cwc.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: > On Wed, 08 Mar 2006 06:20:42 +0000, Steve Holden > declaimed the following in comp.lang.python: > >>Hang around here long and you'll see a bunch of people waiting on >>replies to questions Google could have given them far quicker. If we >>weren't paid thousands of dollars a week to answer questions on this >>list we'd probably get snarky more often. > > What! Why didn't anyone tell me where to submit my timecard? It's by the *byte*, Dennis. How did you think Alex managed all that time off real work to write a book on Python (like anyone buys those)? ;-) -Peter From johnwadeunderwood at yahoo.com Mon Mar 27 18:32:41 2006 From: johnwadeunderwood at yahoo.com (John) Date: 27 Mar 2006 15:32:41 -0800 Subject: instantiate a class with a variable Message-ID: <1143502361.763073.293340@u72g2000cwu.googlegroups.com> Hi, is it possible to instantiate a class with a variable. example class foo: def method(self): pass x='foo' Can I use variable x value to create an instance of my class? Thanks, John From g.brandl-nospam at gmx.net Fri Mar 31 02:51:23 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Fri, 31 Mar 2006 09:51:23 +0200 Subject: Why are so many built-in types inheritable? In-Reply-To: References: <441c6498$1_1@news.cybercity.ch> <1143730846.459218.306370@i39g2000cwa.googlegroups.com> Message-ID: <4945brFmrjrrU1@individual.net> Antoon Pardon wrote: > Op 2006-03-30, Michele Simionato schreef : >> I cannot find the reference now, but I remember Tim Peters saying some >> time ago that the only >> reason why FunctionType is not subclassable is that nobody bothered to >> write a patch for it. > > The question then is, why is there a need for such a patch? > > I mean when types and classes became unified and ints, lists ... became > subclassable one would think that in all those new code that had to be > written, it wouldn't have been that difficult to see to it that all > types became subclassable. I find it hard to believe that in the > unification period the decision to make one type subclassable and > an other not was made solely on the basis that a patch was submitted > for the first but not for the other. It's not that hard to understand, is it? Whoever made the builtin types new- style types didn't add the BASETYPE flag to function or slice. Apparently he thought it wasn't worth the effort as he couldn't imagine a use case for it. So, when someone had liked them to be subclassable, he'd have written a patch. Georg From robert.kern at gmail.com Mon Mar 6 15:50:37 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 06 Mar 2006 14:50:37 -0600 Subject: reshape a list? In-Reply-To: <1141677595.143157.296740@v46g2000cwv.googlegroups.com> References: <1141677595.143157.296740@v46g2000cwv.googlegroups.com> Message-ID: KraftDiner wrote: > I have a list that starts out as a two dimensional list > I convert it to a 1D list by: > > b = sum(a, []) > > any idea how I can take be and convert it back to a 2D list? Alternatively, you could use real multidimensional arrays instead of faking it with lists. http://numeric.scipy.org In [15]: import numpy In [16]: tmp = numpy.arange(256)**2 In [17]: a = numpy.column_stack((a,)*256) In [18]: a[:10,:10] Out[18]: array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [16, 16, 16, 16, 16, 16, 16, 16, 16, 16], [25, 25, 25, 25, 25, 25, 25, 25, 25, 25], [36, 36, 36, 36, 36, 36, 36, 36, 36, 36], [49, 49, 49, 49, 49, 49, 49, 49, 49, 49], [64, 64, 64, 64, 64, 64, 64, 64, 64, 64], [81, 81, 81, 81, 81, 81, 81, 81, 81, 81]]) In [19]: a.shape Out[19]: (256, 256) In [20]: a.ravel()[:100] Out[20]: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) In [21]: a.ravel().shape Out[21]: (65536,) In [22]: b = numpy.reshape(a.ravel(), (256,256)) In [23]: b.shape Out[23]: (256, 256) In [24]: (a == b).all() Out[24]: True -- Robert Kern robert.kern at gmail.com "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 duncan.booth at invalid.invalid Thu Mar 16 10:50:21 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Mar 2006 15:50:21 GMT Subject: Python Documentation Standards References: Message-ID: Steven Bethard wrote: > Colin J. Williams wrote: >> Doc strings provide us with a great opportunity to illuminate our code. >> >> In the example below, __init__ refers us to the class's documentation, >> but the class doc doesn't help much. > > It doesn't? > > >>> print list.__doc__ > list() -> new list > list(sequence) -> new list initialized from sequence's items > > What is it you were hoping to see in constructor documentation? > > STeVe How about this?: >>> print list.__doc__ list() -> new list list(sequence) -> new list initialized from sequence's items See http://docs.python.org/lib/built-in-funcs.html#l2h-44 although it would be better if the online docs had a more permanent looking anchor. From g.brandl-nospam at gmx.net Tue Mar 14 08:03:34 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Tue, 14 Mar 2006 14:03:34 +0100 Subject: andmap and ormap In-Reply-To: References: <1142339035.687474.271120@p10g2000cwp.googlegroups.com> <1142339421.5045.3.camel@kenshin> Message-ID: <47nt96Fgfv8kU1@individual.net> Joel Hedlund wrote: >> footnote: if you have a recent Python 2.5 build, > > Who would have that? Is it a good idea to use a pre-alpha python version? > Or any unrealeased python version for that matter? I was under the impression that > the recommended way to go for meager developers in python like myself is to stick > with the latest stable production release (2.4.2 at the time of writing I believe). > Or should I start grabbing the Subversion trunk on a nightly basis? As most of the new features 2.5 is going to have are already implemented, it's quite possible that people do checkout the SVN trunk and play with them. Course, Fredrik could have said "In 2.5 you'll be able to write..." Georg From davidworley at gmail.com Wed Mar 15 16:59:41 2006 From: davidworley at gmail.com (Dave) Date: 15 Mar 2006 13:59:41 -0800 Subject: Loop Backwards In-Reply-To: References: <1139883877.323042.199040@o13g2000cwo.googlegroups.com> <43f19e0f$0$4761$636a55ce@news.free.fr> Message-ID: <1142459981.689594.261150@u72g2000cwu.googlegroups.com> >> or (more perlish at first sight): >> for item in alist[::-1]: >> do_something_with(item) >No "or" here. The [::-1] version creates a whole new list in memory, >it's silly to believe both will behave equally (well, strictly speaking >they will, but one will use twice more memory than the other). Thank you for your reply. Please be mindful of making statements such as: "it's silly to believe both will behave equally" One of the greatest weaknesses of Python is the less than friendly attitude Pythonistas display towards one another. Bruno's suggestions were valid, given the original question. Even if I had asked for the most efficient method of iterating through a list in reverse, this response is unwarranted. This example is why everyone is more excited about Ruby than Python. If we become more friendly to each other, Python will win! From a_salnikov at yahoo.com Wed Mar 8 17:29:44 2006 From: a_salnikov at yahoo.com (Andy Salnikov) Date: Wed, 8 Mar 2006 14:29:44 -0800 Subject: Python advocacy in scientific computation References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> <1141583453.403143.189400@i40g2000cwc.googlegroups.com> <1141750637.180979.69890@j33g2000cwa.googlegroups.com> Message-ID: "Steve Holden" wrote in message news:mailman.2875.1141799254.27775.python-list at python.org... > Andy Salnikov wrote: >> "Michael Tobis" wrote in message >> news:1141750637.180979.69890 at j33g2000cwa.googlegroups.com... >> >>> >>>When you say "all kinds" of inlined code, do you have any other >>>examples besides HTML? >>> >> >> Makefiles is one example. Shell script containing snippet(s) of >> Python code is another one. >> >> At one time I also tried to make a simple "configuration file" >> engine based on Python for a big Framework used in one physics lab. >> Idea was to have a Python extension for that C++ framework and >> to configure the Framework from Python code, like: >> >> # Module means C++ Framework module, not Python >> >> Module1.param1 = "a string" >> Module2.paramX = [ 1, 2, 3 ] >> # etc., with all Python niceties. >> >> People who were using this Framework were all hard-core physicists, >> some of them knew Fortran, many were exposed to C++. There were >> few other "languages", some of them home-grown, used for different >> tasks, but none of these mentioned languages ever placed so much >> significance on the whitespaces. There were some big surprises for >> people when they discovered they can't arbitrary indent pieces of >> the above configuration files because it is all Python code. Add >> here space/tabs controversy if it is not enough yet to confuse >> poor physicist fellows :) I think that config file project was killed >> later in favor of less restrictive format (I left the lab before that, >> can't say for sure.) >> > I just hope this remains a "someone made a poor choice of configuration > language and trained the users inadequately" story, and does not > transmogrify into a "Python is bad" story. > It does not, and I did not say it's "bad". But people do percieve it as at least very weird kind of language in a modern times of all the "curly brace languages". > You mention makefiles and shell scripts as contexts unsympathetic to > Python's indentation requirements, but frankly you don't see much code in > any language except shell inlined in these contexts. > Shell's strength is in the process spawning/management and input/output redirection, Python is rather weak in that area but OTOH Python is strong in processing highly structured and numeric data, where shells are really weak. I saw lots of awk or sed "code" embedded in scripts so your claim that nothing except sheel is being inlined does not look right to me. > Given the makefile's requirement that significant leading whitespace be > tabs and not spaces and you have a recipe for disaster inlining any > language. > I saw makefiles with thousands lines of Perl code in them. I agree this (Perl) is disaster, but it would probably be better if it was Python code instead. Andy. From johnjsal at NOSPAMgmail.com Wed Mar 8 23:10:56 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Mar 2006 23:10:56 -0500 Subject: advice on this little script In-Reply-To: <2bSdncqWK7aJN5LZRVn-vA@rcn.net> References: <2bSdncqWK7aJN5LZRVn-vA@rcn.net> Message-ID: <2bSdncWWK7aINpLZRVn-vA@rcn.net> John Salerno wrote: > sleep(1.0) Heh heh, that was for testing. Obviously it should read 60.0 (is a float necessary at all?). From deets at nospam.web.de Thu Mar 23 09:04:59 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 23 Mar 2006 15:04:59 +0100 Subject: question: how to clare the absolute url in a html file References: <1143115467.871625.158730@g10g2000cwb.googlegroups.com> <48fjb6FjnjhpU2@uni-berlin.de> <1143118480.301107.317420@e56g2000cwe.googlegroups.com> Message-ID: <48foa0Fk40odU1@uni-berlin.de> dongdong wrote: > to Diez B. Roggisch : > no, I won't to use this way, its efficiency is very low as I need to > replace all the '", line 365, in ? File "", line 155, in install File "", line 94, in LoadSystemModule ImportError: DLL load failed: A device attached to the system is not functioning. *** run_installscript: internal error 0xFFFFFFFF *** When I try to run a script using the socket library (also trying to start Stani's Python Editor) I get the following message:- File "C:\APPS\PYTHON\242\lib\SocketServer.py", line 132, in ? import socket File "C:\APPS\PYTHON\242\lib\socket.py", line 45, in ? import _socket ImportError: DLL load failed: One of the library files needed to run this applic ation cannot be found. Is it the same dll in both cases, any idea what it might be and where could I find a copy? Many thanks, John Pote From steven.bethard at gmail.com Wed Mar 8 02:10:11 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 08 Mar 2006 00:10:11 -0700 Subject: New python.org website In-Reply-To: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> References: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> Message-ID: Phoe6 wrote: > beta.python.org evolved very nice and noticed today the new python.org > website going live. There is a change in the look n feel, wherein it > looks "more official" and maximum possible information about python is > now directly accessible from the home page itself. Kudoes to the > design team. I want to second that! A moment aside to all the complainers. If you don't like the format, color scheme, etc., could you take a half an hour and mock up a better format that shows what you'd like to see? Honestly, if you come up with a style that everyone agrees is better than what's there now, I'd bet people would be glad to change it. Especially if it's just switching a CSS stylesheet. STeVe From rajesh1986 at gmail.com Wed Mar 29 10:43:20 2006 From: rajesh1986 at gmail.com (Rajesh Sathyamoorthy) Date: Wed, 29 Mar 2006 23:43:20 +0800 Subject: zipfile module Message-ID: <47a726d60603290743h8709ffale0167b0c7dde1d2c@mail.gmail.com> Hi, I know how to write files to a zip file but i was wondering if there was a way to add a empty folder to the zip file using the zipfile module? I can only write files and not directories to a zip file. Thank You. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Mon Mar 6 14:18:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 6 Mar 2006 20:18:30 +0100 Subject: how about adding ping's uuid module to the standard lib ? Message-ID: see subject and http://python.org/sf/1368955 comments ? From cito at online.de Mon Mar 20 10:23:59 2006 From: cito at online.de (Christoph Zwerschke) Date: Mon, 20 Mar 2006 16:23:59 +0100 Subject: ** Operator In-Reply-To: <1142864492.645457.291240@j33g2000cwa.googlegroups.com> References: <1142833145.976550.104830@v46g2000cwv.googlegroups.com> <1142833540.860154.137040@u72g2000cwu.googlegroups.com> <1hcgw5p.1ufznwe1lxeagfN%aleaxit@yahoo.com> <1142864492.645457.291240@j33g2000cwa.googlegroups.com> Message-ID: Ziga Seilnacht wrote: > Christoph Zwerschke wrote: >> In the explanation about pow() at >> http://docs.python.org/lib/built-in-funcs.html, the notation 10**2 is >> suddenly used, without explaining that it is equivalent to pow(10,2). I >> think this could be improved in the docs. > > It is: > http://docs.python.org/lib/typesnumeric.html You're right, it's mentioned there in section 2.3.4, but the explanation of pow() is already in section 2.1 prior to that. So it would be nice if the paragraph explaining pow() would mention that you can also write x**y for pow(x,y). And/or the example given in the paragraph should say pow(10,2) instead of 10**2. Otherwise it's a bit confusing for somebody who reads in chronological order and doesn't know about the ** syntax (many other languages write x^y instead of x**y). -- Christoph From sullivanz.pku at gmail.com Tue Mar 7 02:36:08 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 6 Mar 2006 23:36:08 -0800 Subject: It is fun.the result of str.lower(str()) Message-ID: <1141716968.656842.57100@v46g2000cwv.googlegroups.com> Guess what would be the result of these functions: >>>str.lower('ASFA') >>>str.join(str(),['1','1','1']) >>>str.join('a','b') If you guess them correctly, please explain. From deets at nospam.web.de Fri Mar 10 09:18:51 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 10 Mar 2006 15:18:51 +0100 Subject: import and shared global variables References: Message-ID: <47dg9iFequsdU1@uni-berlin.de> > I'm implementing a plugin-based program, structured like the example > below (where m1 in the main module, loading m2 as a plugin). I wanted > to use a single global variable (m1.glob in the example) to store some > config data that the plugins can access. However, the output shown > belown seems to imply that glob is *copied* or recreated during the > import in m2. Am I missing something? I thought m1 should be in > sys.modules and not be recreated during the import in m2. Yes, you are missing that your first glob is in __main__.glob, _not_ in m1.glob. To make that happen, use something like this: glob = [1] def main(): pass if __name__ == "__main__": import m1 m1.main() Diez From jstroud at ucla.edu Tue Mar 7 15:26:00 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 07 Mar 2006 12:26:00 -0800 Subject: inserting into a list In-Reply-To: References: <475qs4Fdp9mhU1@uni-berlin.de> Message-ID: John Salerno wrote: > Diez B. Roggisch wrote: > >> Why don't you just _try_ that? It would have been way faster than to ask >> questions you can easily answer yourself. > > > I did try it, but I was still hoping for an explanation, which I've also > gotten from you guys, some in nicer terms than others. People who answer questions on this list have forgotten how unintuitive intuitive can be. In other words, they have found that the intuitive way to do things in python is usually the right way, which may not be the case in other languages. Thus, your instinct to see if your instincts are correct rings as laziness here, when in fact you are just being rigorous. Here is one my favorite examples of python intuitiveness: if something is not something_else: do_whatever() Who would have thunk it? James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From reply.in.the.newsgroup at my.address.is.invalid Fri Mar 10 07:46:10 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 10 Mar 2006 13:46:10 +0100 Subject: how to validate a proxy is alive? References: <1141994373.525265.165060@i39g2000cwa.googlegroups.com> Message-ID: JuHui: >If a proxy is alive then return true, else return fals after 1 second. What kind of proxy? Design pattern? Protocol? Which one? -- Ren? Pijlman From onurb at xiludom.gro Tue Mar 7 04:23:59 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 07 Mar 2006 10:23:59 +0100 Subject: It is fun.the result of str.lower(str()) In-Reply-To: <1141716968.656842.57100@v46g2000cwv.googlegroups.com> References: <1141716968.656842.57100@v46g2000cwv.googlegroups.com> Message-ID: <440d515d$0$12876$626a54ce@news.free.fr> Sullivan WxPyQtKinter wrote: > Guess what would be the result of these functions: s/functions/method calls/ > >>>>str.lower('ASFA') => 'ASFA'.lower() => 'asfa' >>>>str.join(str(),['1','1','1']) => ''.join(['1','1','1']) => '111' >>>>str.join('a','b') => 'a'.join('b') => 'b' > > If you guess them correctly, No need to guess, there's this thing named the python interactive shell, you know... And it even has an integrated help system. > please explain. Explain what ? It's all in the fine manual. * Klass() is a call to Klass's constructor and returns an instance of Klass. * Klass.method(klass_instance) is the same as klass_instance.method() * str is the builtin string class. * without any args, the str constructor returns an empty string * str.join() takes a sequence of strings and join'em with the target str instance as separator Now would you be kind enough to explain what's funny about all this ? -- 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 Mon Mar 6 13:27:35 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 6 Mar 2006 19:27:35 +0100 Subject: copying a tuple to a list.. References: <1141666930.931617.58180@j52g2000cwj.googlegroups.com> Message-ID: sergio at village-buzz.com enlightened us with: > i have a result tuple from a MySQLdb call that would like to change in > place.. > > i would like to copy it to a list, so i can modify it in place, but i > cannot figure out how to do it. dataResults = (1, 2, 12) dataList = list(dataResults) 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 a.schmolck at gmail.com Mon Mar 20 16:17:07 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 20 Mar 2006 21:17:07 +0000 Subject: Programming challenge: wildcard exclusion in cartesian products References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> <441ef3a2$0$15789$14726298@news.sunsite.dk> <1142886321.996690.78600@t31g2000cwb.googlegroups.com> Message-ID: joswig at corporate-world.lisp.de writes: > (defun >> (val num-bytes) > "Right-shift positive integer val by num-bytes" > (floor (/ val (expt 2 num-bytes)))) or just (floor val (expt 2 num-bytes)) 'as From josecarlos.balderas at gmail.com Fri Mar 31 06:54:28 2006 From: josecarlos.balderas at gmail.com (Jose Carlos Balderas Alberico) Date: Fri, 31 Mar 2006 13:54:28 +0200 Subject: Working with files in a SimpleXMLRPCServver Message-ID: I'm setting up a server accepting XML-RPC calls using the SimpleXMLRPCServer class. Basically, what I have to do is send a zip-compressed file to the server, have the server unzip it and process it, after processing it the server is supposed to zip the file again, and send it back to the client. I found a solution, but wanted to ask you if you think there's an easier way of doing this. What I do at the client first is to compress the file (which is a .txt) using os.system("zip blah blah.txt"). Then I obtain the name of the compressed file (let's assume it is blah.zip). Once I have the name of the zip file, I do the following: *fd = open("blah.zip", 'r') bin = xmlrpclib.Binary(fd.read())* *server.process(bin)* I obtain a file descriptor, read the data and stuff it in a Binary object, and send it to the server as a parameter to the process method. Then, at the server script, I create a file, and write into it the data contained in that Binary object using the attribute .data. That way I'll have a new file with the data passed to the server. Then again I use os.system(...) to unzip the data and recover the original content. When I need to send content back to the client, the whole process is repeated. My question is: do you think this is an appropiate way to exchange files between client and server? I'm relativately new to Python, and the task of the file exchange has been assigned to me. I haven't been able to find documentation on the subject, so any help would be appreciated. If you need any more information about what I'm trying to do, just ask. Thank you so much for your attention :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From rrr at ronadam.com Wed Mar 29 19:47:06 2006 From: rrr at ronadam.com (Ron Adam) Date: Wed, 29 Mar 2006 18:47:06 -0600 Subject: any() and all() on empty list? In-Reply-To: <1143630405.344694.269060@u72g2000cwu.googlegroups.com> References: <1143630405.344694.269060@u72g2000cwu.googlegroups.com> Message-ID: Carl Banks wrote: > Steve R. Hastings wrote: >> I'm completely on board with the semantics for any(). But all() bothers >> me. If all() receives an empty list, it will return True, and I don't >> like that. To me, all() should be a more restrictive function than any(), >> and it bothers me to see a case where any() returns False but all() >> returns True. > > Perhaps a practical example will illustrate why all() returns False > better than all this mathematical mumbo-jumbo. > > Ok, say you're writing a simple software management/bug tracking > system. It manage another software package that is to have periodic > releases, but the release can only be made when there are no > outstanding bugs. You might have a line of code that looks like this: > > if all(bug.status == 'closed' for bug in bugs_filed): > do_release() > > As you can see, the release will only happen if all the bugs are marked > closed. But... what if no bugs have been filed? If all() were to > return False on an empty sequence, the software couldn't be fixed until > at least one bug had been filed and closed! > > The point is, whenever you have to test that every item in a list is > true, it is almost always correct for the test to pass when the list is > empty. The behavior of all() is correct. > > > Carl Banks Yes, But that should be a test for 'not any()'. if not any(bug.status == 'open' for bug in bugs_filed): do_release() So to give a counter example... Where we are assembling widgets in a manufacturing plant. Where we don't want to go to the next step until *all* the sub parts are present. if all(part.status == 'present' for part in unit): do_release() Oops! Some empty bins showed up at the next assembly station. ;-) Cheers, Ron From david.humpherys at gmail.com Tue Mar 7 21:02:49 2006 From: david.humpherys at gmail.com (david.humpherys at gmail.com) Date: 7 Mar 2006 18:02:49 -0800 Subject: linux clipboard? In-Reply-To: References: <1141773655.057852.34430@j33g2000cwa.googlegroups.com> Message-ID: <1141783369.652706.4540@u72g2000cwu.googlegroups.com> ah.. ok. gnome it is. are there py commands for gnome? From cito at online.de Thu Mar 23 18:35:44 2006 From: cito at online.de (Christoph Zwerschke) Date: Fri, 24 Mar 2006 00:35:44 +0100 Subject: Multiplying sequences with floats Message-ID: Currently, if you write 3*'*', you will get '***', but if you write 3.0*'*', you will get an error (can't multiply sequence by non-int). I was wondering whether this should be allowed, i.e. multiplication of a sequence with a float. There could be either an implicit typecast to int (i.e. rounding), or the above error could occur only for floats with a fractional part. Usage example: You want to convert a percentage value (to a number of 0 to 4 stars. You could do this with the expression percentage/20*'*' However, this fails if percentage is a float. And even this fails: percentage//20*'*' So you have to write int(percentage//20)*'*' in which case you may as well write int(percentage/20)*'*' again. Ok, it's probably not a big deal but it somehow stroke me as odd that you can't simply write percentage//20*'*'. -- Christoph From John-Whitlock at ieee.org Fri Mar 24 10:39:41 2006 From: John-Whitlock at ieee.org (JW) Date: 24 Mar 2006 07:39:41 -0800 Subject: Multiplying all the values in a dictionary References: <1143162298.28477.7.camel@cornell> <1143165699.692995.3220@e56g2000cwe.googlegroups.com> <1143177799.833144.108400@t31g2000cwb.googlegroups.com> Message-ID: <1143214781.602511.8950@i40g2000cwc.googlegroups.com> As long as you are optimizing, addition is slightly faster than multiplication: $ python2.4 -mtimeit 'h=1;h*=2' 1000000 loops, best of 3: 0.286 usec per loop $ python2.4 -mtimeit 'h=1;h=h+h' 1000000 loops, best of 3: 0.23 usec per loop Of course, that's only a 20% decrease, so it might not be worth the trouble. From Serge.Orlov at gmail.com Sun Mar 26 22:57:59 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 26 Mar 2006 19:57:59 -0800 Subject: What's the best way to learn perl for a python programmer? References: <1143213419.350106.274060@g10g2000cwb.googlegroups.com> Message-ID: <1143431879.238898.145890@j33g2000cwa.googlegroups.com> vj wrote: > I've been given a project which requires writing scripts that need to > be run on over 3000 servers. Only about 15% of them have python > installed on them. While all/most of them will have perl. I used to work for a company with hundreds of development workstations and build/test servers, different operating systems (add to the mixture regular disk failures and regular hiring of new people). Everything was controlled by pretty big perl scripts and people who maintained all the tools found that using perl from distributions was a hassle because of differences between perl versions and the need to install it if OS doesn't have it. So they just built several (for different OSes/archetectures) relocatable distributions of perl and put them on a network drive. That turned out to be more reliable and more easy to maintain. You can do the same with python. > I'll try and do as much as possible in pexpect but am sure I'll have do > some significant perl. Any suggestions on what is the best way to get > upto speed on perl? Forget about perl :) From robin at alldunn.com Tue Mar 28 13:03:31 2006 From: robin at alldunn.com (Robin Dunn) Date: Tue, 28 Mar 2006 10:03:31 -0800 Subject: ANNOUNCE: wxPython 2.6.3.0 Message-ID: <44297A73.6000400@alldunn.com> Announcing ---------- The 2.6.3.0 release of wxPython is now available for download at http://wxpython.org/download.php. There have been many enhancements and fixes implemented in this version, many of which are listed below and at http://wxpython.org/recentchanges.php. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit Microsoft Windows, most Linux or other Unix-like systems using GTK2, and Mac OS X 10.2+, in most cases the native widgets are used on each platform. Changes in 2.6.3.0 ------------------ Change the wx.ListCtrl InsertStringItem wrapper to use the form that takes an imageIndex, and set the default to -1. This ensures that on wxMSW that if there is an image list but they don't specify an image, the native control doesn't use one anyway. wxMSW: wx.ListCtrl in report mode is now able to support images in other columns besides the first one. Simply pass an image index to SetStringItem. For virtual list controls you can specify the image to use on the extra columns by overriding OnGetItemColumnImage in your derived class. It is passed the item number and the column number as parameters, and the default version simply calls OnGetItemImage for column zero, or returns -1 for other columns. Switched to using SWIG 1.3.27 for generating the wrapper code. There are some small changes needed to SWIG to work around some bugs that wxPython exposes, and to be able to generate code that matches that which wxPython is using. If you are building wxPython yourself and need to modify any of the *.i files or to add your own, then you will want to be sure to use a matching SWIG. See wxPython/SWIG/README.txt in the source tarball for details. wx.Image.Copy now also copies the alpha channel. wxMSW: Fixed problem in wx.TextCtrl where using SetValue and wx.TE_RICH2 would cause the control to be shown if it was hidden. wxMSW: Numpad special keys are now distinguished from normal keys in key events. wxMSW: Multiline notebook tab label change now resizes the control correctly if an extra row is removed or added. wxMSW: On XP fall back to unthemed wxNotebook if specified orientation not available in the themed version. Added wx.Toolbar.GetToolsCount. Added wx.GridSizer.CalcRowsCols. Added wx.OutputStream.LastWrite. wxGTK: EVT_SET_CURSOR is now sent. wxGTK: Fix RequestMore for idle events. wxGTK: Implement user dashes for PS and GNOME printing. wxGTK: Correct update region code. Don't always invalidate the whole window upon resize. Reenable support for thewx.NO_FULL_REPAINT_ON_RESIZE flag. Also disable refreshing custom controls when focusing in and out. wx.lib.pubsub: Publisher is now able to parse a dotted notation string into a topic tuple. For example: subscribing to "timer.clock.seconds" is the same as subscribing to ("timer", "clock", "seconds"). Applied patch #1441370: lib.plot - allow passing in wx.Colour() Added wx.CommandEvent.GetClientData. Updated wxStyledTextCtrl to use version 1.67 of Scintilla. NOTE: The STC_LEX_ASP and STC_LEX_PHP lexers have been deprecated, you should use STC_LEX_HTML instead. wxSTC: Implemented fix for SF Bug #1436503. Delay the start of the DnD operation in case the user just intended to click, not drag. Updated the analogclock.py module to the new analogclock package from E. A. Tacao. Added the wx.lib.mixins.listctrl.CheckListCtrlMixin class from Bruce Who, which makes it easy to put checkboxes on list control items. Applied a patch from Christian Kristukat to wx.lib.plot that adds scrollbars when the plot is zoomed in, and also the ability to grab a zoomed plot and move it around with a mouse drag. XRCed updated to allow wxMenuBar to be created inside a wxFrame. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From brochu121 at gmail.com Thu Mar 30 16:03:18 2006 From: brochu121 at gmail.com (david brochu jr) Date: Thu, 30 Mar 2006 16:03:18 -0500 Subject: Popen Message-ID: <9583ed900603301303w11fb981egd0a83f01d95d4ffd@mail.gmail.com> I am trying to write a script that starts a window process and then continues on to do other testing, but have encountered a little problem. When I start the exe (process to run) I cannot move on past that point in my script. Once started, the process is supposed to run in the background continuously and this is the reason my script stalls after starting the process. I have tried to initiate the process using os.system and os.popenand both run into the same problem. Is there a work around for this? Thanks, Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Mar 3 04:39:14 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 03 Mar 2006 04:39:14 -0500 Subject: Convert dictionary to HTTP POST In-Reply-To: <4408084D.4060708@designaproduct.biz> References: <4408084D.4060708@designaproduct.biz> Message-ID: Laszlo Zsolt Nagy wrote: > Hello, > > How can I convert a dictionary into a HTTP POST string? > I have an example below, but this is not working correctly for special > characters. (" ' and others). In other words, if I use "Bessy's cat" > instead of "Bessy" then the http server will parse that to "Bessy's cat" > Probably the problem is that I should not use urllib.quote but something > else. > Can you please advise? > > Laszlo > > form_values = {'name':'Bessy','age':'10','gender':'female'} > for key,value in form_values.iteritems(): > values.append('%s=%s' % (urllib.quote(key),urllib.quote(value)) ) > > values.append('x=33') > values.append('y=14') > post_data = ('&'.join(values)).replace('/','%2F') > txheaders = { > > 'Accept':'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', > 'Accept-Language':'en,hu;q=0.8,en-us;q=0.5,hu-hu;q=0.3', > 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', > } > req = urllib2.Request(url, post_data, txheaders) > u = urllib2.build_opener() > req.add_data(post_data) > page2 = self.download(action,post_data,{ > 'Content-Type': 'application/x-www-form-urlencoded' > }) > openerdirector = u.open(req) > data = openerdirector.read() > See urllib.urlencode(). No idea why they don't include it in urllib2 as well, but there you go. >>> from urllib import urlencode >>> urlencode({'a':'& "Simple string"', 'b': '<>!@#$%^&*()_+='}) 'a=%26+%22Simple+string%22&b=%3C%3E%21%40%23%24%25%5E%26%2A%28%29_%2B%3D' >>> regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From //phr.cx at -dot-invalid.no-spam.invalid Mon Mar 13 16:57:10 2006 From: //phr.cx at -dot-invalid.no-spam.invalid (Paul Rubin) Date: 13 Mar 2006 21:57:10 GMT Subject: Python Love :) References: <1142099350.122968.35220@i39g2000cwa.googlegroups.com> Message-ID: <4415eab6$0$77018$892e7fe2@authen.yellow.readfreenews.net> "gregarican" writes: > reversed(a_string) (python) > > Which version of Python offers this function? It doesn't seem to be > available in the 2.3 version I have installed... > I think it's new in 2.4. From maxkhesin at gmail.com Fri Mar 3 15:06:07 2006 From: maxkhesin at gmail.com (xamdam) Date: 3 Mar 2006 12:06:07 -0800 Subject: no-setup packages? Message-ID: <1141416367.750029.238980@i39g2000cwa.googlegroups.com> Hi all, we have a situation where I need to deploy some python modules without superuser permissions - is there a 'standard' way of doing it? Better yet, is there a way to deploy modules without running any scripts at all? Tarball deployment of some sort? Particular things I have in mind are cx_Oracle, Cheetah. thanks, max From giacomo.boffi at polimi.it Mon Mar 27 10:15:21 2006 From: giacomo.boffi at polimi.it (Giacomo Boffi) Date: Mon, 27 Mar 2006 17:15:21 +0200 Subject: tkinter+matplotlib Message-ID: i have coded some progs that use the Pmw.Blt.Graph widgets, embedded in a simple Tkinter GUI ,---- | from Tkinter import * | import Pmw | ... | frame=Frame(root) | ... | graph=Pmw.Blt.Graph(frame,...) | graph.line_create(...) | graph.pack(...) `---- now i'd like to port those progs to an environment where i have no BLT assuming that i can use matplotlib to draw the line graphs i need, how do i place the graph widget inside my tkinter GUI? tia, gb -- If you grow tired of the friends you make Never ever turn the back on them Say they were the best of time you ever had The best of times with the thougthless kind -- John Cale From arkanes at gmail.com Sat Mar 4 21:52:36 2006 From: arkanes at gmail.com (Chris Mellon) Date: Sat, 4 Mar 2006 20:52:36 -0600 Subject: XP rich text cut-n-paste In-Reply-To: <1141501151.073307.281850@u72g2000cwu.googlegroups.com> References: <1141501151.073307.281850@u72g2000cwu.googlegroups.com> Message-ID: <4866bea60603041852s352a0c74ta2c2b52309857bed@mail.gmail.com> On 4 Mar 2006 11:39:11 -0800, Paddy wrote: > Hi, > Is their a colourized editor/shell that allows you to cut and paste the > colourized text? > > Idle, SPE, Eclipse, and pythonwin all seem to nicely colourize both > command line input as well as editor windows but when I cut and paste > (in this case, into OpenOffice Writer), even the paste-special menu > just allows the pasting of un-adorned text. > > i have a work-around: gvim coourizes and allows export as html, but it > is long-winded. > The SciTe editor has a "Copy as RTF" function. It uses the same editor control as SPE (but not idle, eclipse, or pythonwin), so you might ask for it as a feature request in SPE. > Thanks in advance, Paddy. > > -- > http://mail.python.org/mailman/listinfo/python-list > From claudio.grondi at freenet.de Wed Mar 1 11:19:13 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 01 Mar 2006 17:19:13 +0100 Subject: why? [win32com/WMI] In-Reply-To: References: Message-ID: Sergey wrote: > import win32com.client > > loc = win32com.client.Dispatch("WbemScripting.SWbemLocator") > svc = loc.ConnectServer("srv", "root/cimv2", "Admin at zzz.ru", "******") > sys = svc.get("Win32_Process") > sys.create("notepad.exe") > > => > > Traceback (most recent call last): > File "remote.py", line 6, in ? > sys.create("notepad.exe") > TypeError: 'int' object is not callable > > I have no idea what are you doing in your code or if the following has something to do with your problem, but sometimes it good to know, that Windows requires Unicode strings as parameter and giving full path file names is always better than to rely on some default mechanisms. Claudio From python-url at phaseit.net Mon Mar 20 07:32:56 2006 From: python-url at phaseit.net (Peter Otten) Date: Mon, 20 Mar 2006 12:32:56 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 20) Message-ID: QOTW: "Anything with 'Python' in its name can't market Python well." - Iain Bicking "Who really cares whether NASA uses Python? One thing I learned from having to sit through too many software marketing presentations is that organizations like NASA are to software what the Library of Congress is to books." - Steven Lumos on comp.lang.ruby How would you compare two strings when you don't care about whitespace? Hint: no regular expressions needed. http://groups.google.com/group/comp.lang.python/browse_frm/thread/2ad8fae9cc32e333/b4dc3a17d7502391 Jarek Zgoda's hack seems to be the most reliable way to get localized month names. http://groups.google.com/group/comp.lang.python/browse_frm/thread/7d8e318b9b27a460/8b8283877bc02aa1?tvc=1 Python 2.5 is scheduled for August 19, 2006. Among the highlights are the with-statement simplifying reliable resource acquisition/release and Fredrik Lundh's ElementTree. When bugs due to clever workarounds made it into the standard library Guido finally gave in, so there will be an inline-if/else, too. Use with discretion :-) http://groups.google.com/group/comp.lang.python/msg/f6f95174484c24cc Experienced developers wrestle with thorny deployment issues. http://blog.ianbicking.org/packaging-python.html Is coding a text adventure? Matt Webb and his co-developers think so. They use Python as the tried and tested tool to explore new ideas. http://www.wired.com/news/technology/0,70413-0.html?tw=wn_technology_4 Iain Bicking shares his thoughts about the new python.org website and marketing Python. http://blog.ianbicking.org/python-marketing-2006.html You don't always need a big fat office suite to get your data out of an Excel spreadsheet. http://groups.google.com/group/comp.lang.python/browse_frm/thread/af8f5484123101ae/fd7fb0d4d894dce2?tvc=1 Stackless Python has been ported to Python 2.4.2. http://www.stackless.com/Members/rmtew/pycon2006Result ======================================================================== 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 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://python.sourceforge.net/peps/pep-0042.html 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 kent at kentsjohnson.com Thu Mar 2 20:58:11 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 02 Mar 2006 20:58:11 -0500 Subject: how to overload sqrt in a module? In-Reply-To: References: Message-ID: <44079e05$1_3@newspeer2.tds.net> Michael McNeil Forbes wrote: > I would like to write a module that provides some mathematical functions > on top of those defined in math, cmath etc. but I would like to make it > work with "any" type that overloads the math functions. > > Thus, I would like to write: > > module_f.py > ---- > def f(x): > """ Compute sqrt of x """ > return sqrt(x) > >>>> from math import * >>>> import module_f >>>> module_f.f(3) > > Traceback (most recent call last): > File "", line 1, in ? > File "module_f.py", line 2, in f > return sqrt(x) > NameError: global name 'sqrt' is not defined > > I understand why sqrt is not in scope, but my question is: what is the > best way to do this? You need to import math in the module that uses it. Imports in one module don't (in general) affect the variables available in another module. module_f.py ---- from math import sqrt # more explicit than from math import * def f(x): """ Compute sqrt of x """ return sqrt(x) Kent From John-Whitlock at ieee.org Thu Mar 2 11:43:47 2006 From: John-Whitlock at ieee.org (JW) Date: 2 Mar 2006 08:43:47 -0800 Subject: looking for help about python-sane References: <1141223894.751643.32240@u72g2000cwu.googlegroups.com> <4405e609$1@127.0.0.1> Message-ID: <1141317827.381512.227790@z34g2000cwc.googlegroups.com> Sorry, I can't help much with the issue. You are getting a low-level hardware fault, and not much information is being propagated up throught the system. It's not a Python problem, but something with SANE, and the Python wrapper is just propagating the SANE error to you. I have a few suggestions: - Use a try block, and see if you can recover: try: grabImage(webcam) except _sane.Error, se: print se # but continue See if all you get is errors, or if it's just a once-in-a-while thing. Maybe you should sleep longer when you get an error, to give the system a chance to do something else. - Try to figure out if SANE is printing any logging message. Check the kernel log (dmesg), the normal system log, read SANE man pages, etc. - Read the sane-v4l man page. The one I found on the Internet says it is Alpha software, which means it is highly experimental, but maybe it has improved. - Try a similar task using the native sane tools (sane-find-scanner, scanimage, etc.). This may generate more useful error messages. - Post a question to the SANE mailing lists: http://www.sane-project.org/mailing-lists.html Once you have a happy SANE setup, then it should be trivial modify the Python code to do the same thing. Hope this is some help, JW From fredrik at pythonware.com Fri Mar 24 17:16:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 24 Mar 2006 23:16:26 +0100 Subject: Strings and % sign fails - Help Please References: <1143168531.461348.130160@t31g2000cwb.googlegroups.com><1143169736.507783.95460@z34g2000cwc.googlegroups.com> <1143237183.175793.49660@t31g2000cwb.googlegroups.com> Message-ID: Siah wrote: > Problem Solved. The problem was with psycopg.Binary whose mere job is > to convert bytes into clear text for sql statement. no, its job is to wrap strings that contain binary blobs, so that data binding works properly. you're supposed to do cursor.execute(statement, Binary(data)) and not cursor.execute(Binary(statement)) or cursor.execute("some statement %s" % Binary(statement)) or some other sillyness. it's an object wrapper, not an escape function for arbitrary SQL. Python's not PHP. for more details, see "Type Objects and Constructors" on this page http://www.python.org/dev/peps/pep-0249/ From bj_666 at gmx.net Thu Mar 9 18:40:29 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 10 Mar 2006 00:40:29 +0100 Subject: linux clipboard? References: <1141773655.057852.34430@j33g2000cwa.googlegroups.com> Message-ID: In <1141773655.057852.34430 at j33g2000cwa.googlegroups.com>, david.humpherys wrote: > how can i copy text to the linux clipboard? > > I've seen a number of posts explain how to do it with tk.... > is this the only way? > > (i'm not using tk as my gui tool kit.) So what are you using instead? Ciao, Marc 'BlackJack' Rintsch From duncan.booth at invalid.invalid Sat Mar 25 13:12:02 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Mar 2006 18:12:02 GMT Subject: __slots__ References: <1143106365.996810.269780@z34g2000cwc.googlegroups.com> <1hcqwk5.9z7uv51pwbdrbN%aleaxit@yahoo.com> Message-ID: Ron Garret wrote: > aleaxit at yahoo.com (Alex Martelli) wrote: > >> > One other question I did not get answered: is there any >> > simple example of a Pythonic use of __slots__ that does NOT >> > involve the creation of **many** instances. >> >> Since the only benefit of __slots__ is saving a few bytes per instance, >> it's not worth the bother unless there are many instances -- so, the >> answer is 'no'. > > I can think of at least two other benefits to using __slots__: > > 1. If you have a typo in an attribute assignment you get an exception > instead of a latent downstream bug. Only if all classes in the inheritance define __slots__, and don't include __dict__ in their slots. In particular, it means you can never rely on this in any code you write which inherits from a library class over which you have no control. In other words, it is such a risky thing to depend on that you would be much better never to rely on it. Try writing some unit tests instead. > > 2. Implicit documentation. Explicit is better than implicit. From finite.automaton at gmail.com Fri Mar 24 14:55:44 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 24 Mar 2006 11:55:44 -0800 Subject: overlapping sets In-Reply-To: <1143183343.525253.251430@i39g2000cwa.googlegroups.com> References: <1143183343.525253.251430@i39g2000cwa.googlegroups.com> Message-ID: <1143230144.911789.294270@t31g2000cwb.googlegroups.com> There is a sets.Set class built in to Python. You might want to use this instead of lists. It defines some handy set operations like intersection, union, and so on. from sets import Set my_sets = { 'one' : Set([0,4,7,9]), 'two' : Set([0,3,7,9]), etc... } From __peter__ at web.de Wed Mar 8 05:45:34 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 08 Mar 2006 11:45:34 +0100 Subject: class variables for subclasses tuple References: <1141809649.911658.90570@p10g2000cwp.googlegroups.com> <1141812400.569624.256460@i39g2000cwa.googlegroups.com> Message-ID: alainpoint at yahoo.fr wrote: > > Peter Otten wrote: >> alainpoint at yahoo.fr wrote: >> >> > Point.x=0 leads to having p.x==0 >> > It seems not possible to have class variables and instance variable >> > having the same name and yet different values. >> >> A quick check: >> >> >>> class T(tuple): >> ... class __metaclass__(type): >> ... x = property(lambda cls: 0) >> ... x = property(lambda self: self[0]) >> ... >> >>> t = T("abc") >> >>> t.x >> 'a' >> >>> T.x >> 0 >> >> So possible it is. Come back if you're stuck generalizing the above. >> >> Peter > > Thanks for your magic answer. > But i am not so good at magic ;-) Once I grokked that a class is just an instance of its metaclass all magic magically vanished :-) > If i want to generalize to a arbitrary number of variables, i got > syntax errors. > Within a class, you can only method/class definitions and assignments. > It is therefore difficult to do something like: > for idx, attr_name in enumerate(attribute_names): > setattr(__metaclass__,attr_name, property(lambda cls:idx) > for idx, attr_name in enumerate(attribute_names): > setattr(T,attr_name, property(lambda self:self[idx]) > > Alain I'm not getting syntax errors: >>> names = "xyz" >>> class T(tuple): ... class __metaclass__(type): ... pass ... for index, name in enumerate(names): ... setattr(__metaclass__, name, property(lambda cls, index=index: index)) ... del index ... del name ... >>> for index, name in enumerate(names): ... setattr(T, name, property(lambda self, index=index: self[index])) ... Traceback (most recent call last): File "", line 2, in ? AttributeError: can't set attribute However, the read-only property of the metaclass prevents setting the class attribute. A workaround is to set the class properties /before/ the metaclass properties. Here is a no-frills implementation, mostly untested: from operator import itemgetter def constgetter(value): def get(self): return value return get def make_tuple(*names): class TupleType(type): pass class T(tuple): __metaclass__ = TupleType def __new__(cls, *args): if len(names) != len(args): raise TypeError return tuple.__new__(cls, args) for index, name in enumerate(names): setattr(T, name, property(itemgetter(index))) for index, name in enumerate(names): setattr(TupleType, name, property(constgetter(index))) return T Peter From anikin#remove_this# at vstu.ru Sun Mar 19 16:18:43 2006 From: anikin#remove_this# at vstu.ru (Dmitry Anikin) Date: Mon, 20 Mar 2006 00:18:43 +0300 Subject: cmp() on integers - is there guarantee of returning only +-1 or 0? Message-ID: <441dd94c$0$20108$834e42db@reader.greatnowhere.com> doc says that it must be > 0, or < 0, but it seems that it returns +1 or -1. Can it be reliably used to get the sign of x: cmp(x, 0) like pascal Sign() function does? I mean, I'm pretty sure that it can be used, but is it mentioned somewhere in language spec, or it may be implementation defined? If so, any other simple means of _reliably_ getting the sign? From jantod at gmail.com Thu Mar 2 14:36:04 2006 From: jantod at gmail.com (jantod at gmail.com) Date: 2 Mar 2006 11:36:04 -0800 Subject: compare classes and not class instances References: <1141292625.252349.155580@e56g2000cwe.googlegroups.com> Message-ID: <1141328164.275347.72840@e56g2000cwe.googlegroups.com> Awesome! Perfect! Thanks Janto From abbi_0382 at yahoo.com Fri Mar 3 00:40:44 2006 From: abbi_0382 at yahoo.com (anushya beauty) Date: Thu, 2 Mar 2006 21:40:44 -0800 (PST) Subject: Importing Files Message-ID: <20060303054044.71439.qmail@web50114.mail.yahoo.com> Hi, I am new to this python. I have installed python 2.4 in my windows xp system. My issue is: i have three directories with some files. ex: Dir ---> Dir1 / file1.1.py " ---> Dir2 / file2.1.py " ---> Dir3 / file3.1.py These are the example directories i have. (Under Dir--->Dir1, Dir2 and Dir3; Under Dir1 --->file1.1.py; Dir2 ---> file2.1.py; Dir3 ----> file3.1.py) In file3.1.py, i am importing the file1.1.py and file2.1.py using the command: from file1.1 import * from file2.1 import * Now, my problem is, file1.1 is imported and i can access the values that are used in that file. But the file2.1 is not imported and returning the error message as "ImportError: No module named file2.1". I couldn't access the var used in that file. Actually, both the files are from different directories only. Then, why onr file is imported and another is not imported?. My Question is: How to import the files from the different directory to the current file?. Anybody please reply me, i have strucked in this simple file importing concept. Thanks and Regards, abbi. --------------------------------- Relax. Yahoo! Mail virus scanning helps detect nasty viruses! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alejandro.weinstein at gmail.com Wed Mar 29 09:49:06 2006 From: alejandro.weinstein at gmail.com (Alejandro) Date: 29 Mar 2006 06:49:06 -0800 Subject: pySerial: write in a blocking mode In-Reply-To: References: <1143578747.023574.150300@i39g2000cwa.googlegroups.com> <1143588343.281554.243620@i40g2000cwc.googlegroups.com> Message-ID: <1143643746.713845.169080@g10g2000cwb.googlegroups.com> Peter Hansen wrote: > Alejandro wrote: > > > > Yes. The device is very simple (I made it). > > Perhaps a very simple change to it would make it as convenient as the > commercial products. I vaguely recall (not having checked for over a > decade) that all they do is set the outgoing DTR line whenever there is > data being transmitted by the PC, by using something like a 555 timer > with a very short delay (effectively watching the start bit and any zero > bits that are transmitted). There are probably even example circuits > based on this or better approaches available on the net. You are right. For instance, the 485COSR converter, from B&B electronics, does precisely that. The schematic is in the datasheet (http://tinyurl.com/ro6qy). I will try this route. Thanks for the help. From alejandro.weinstein at gmail.com Tue Mar 28 18:25:43 2006 From: alejandro.weinstein at gmail.com (Alejandro) Date: 28 Mar 2006 15:25:43 -0800 Subject: pySerial: write in a blocking mode In-Reply-To: References: <1143578747.023574.150300@i39g2000cwa.googlegroups.com> Message-ID: <1143588343.281554.243620@i40g2000cwc.googlegroups.com> Peter Hansen wrote: > Alejandro wrote: > > I'm using pySerial to talk to a RS232 to RS485 converter. In order to > > control the converter, I need to control the DTR line to enable/disable > > de RS485 driver. > > This seems a little odd to me. We've used several RS232-RS485 > converters without needing to do that. Maybe a more sophisticated > device would eliminate this need? Yes. The device is very simple (I made it). > What you're trying to do is a hard realtime operation, and unless it's > directly supported you could be up against an impossible task using > Windows. (But it seems you already knew that. :-) I know it can be difficult/impossible. By the way, I am coding in Linux, but want my code to be portable between Windows and Linux(!). I will rethink the whole issue. May be I will use the time.sleep alternative, taking a good margin to manage the uncertainty of the delay. From steve at REMOVETHIScyber.com.au Thu Mar 9 06:57:03 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 09 Mar 2006 22:57:03 +1100 Subject: Simple questions on use of objects (probably faq) References: Message-ID: On Thu, 09 Mar 2006 12:24:05 +0100, Brian Elmegaard wrote: > James Stroud writes: > >> You should look into __cmp__ and other magic methods. This is probably >> the type of functionality you seem to be after. > > Good example, I need to look at the magic methods. > What I want is to get the value of another variable in C. Would I need to > use __repr__ and get the id from it to find xx of the instance with > maximum x? > > class C: > def __init__(self, x): > self.x = x > self.xx = x*x > > sees = [C(x) for x in (4,7,1,3,0,9,2)] # random-ish ints > print max(sees) Can you explain more carefully what you are trying to do? If you want the square of the maximum value, just do this: max(4,7,1,3,0,9,2)**2 __repr__ is *not* the way to get the ID of a general object: >>> repr(4) '4' For some objects, the default representation includes the ID as part of the representation string, but that's not the way to get the ID. The way to do that is with the id() function. Right, now that you've learnt how to get the ID of an object, scrub it from your mind. You won't need it. You can't use it. It isn't the way to do whatever you are trying to do, whatever it is that you are trying to do. These aren't the droids you are looking for. [The above paragraph is always true, except for the exceptions when it is not true. You will know when you need id(). If you only *think* you need id(), you don't need it.] Seriously though, you can't generally work backwards to see where an object came from (which list, which dictionary, whatever). In general, objects do not know what references there are to that object. If your algorithm relies on object X knowing that it is the 5th item of list L, then you must either store that information yourself somewhere, and maintain it, or you must change your algorithm. -- Steven. From brian at rkspeed-rugby.dk Thu Mar 9 07:23:22 2006 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: Thu, 09 Mar 2006 13:23:22 +0100 Subject: Simple questions on use of objects (probably faq) References: Message-ID: Steven D'Aprano writes: > Can you explain more carefully what you are trying to do? If you want the > square of the maximum value, just do this: I want to get the value of another attribute of the instance with maximum x. I know I could do it like you suggest for the case with x*x, but the other attribute does not depend on x. > [The above paragraph is always true, except for the exceptions when it is > not true. You will know when you need id(). If you only *think* you need > id(), you don't need it.] :-) > algorithm relies on object X knowing that it is the 5th item of list L, > then you must either store that information yourself somewhere, and > maintain it, or you must change your algorithm. OK, I think this is the answer I was looking for. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk From yuxi at ece.gatech.edu Tue Mar 28 10:03:47 2006 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Tue, 28 Mar 2006 10:03:47 -0500 Subject: in-place string reversal In-Reply-To: <1143556185.348035.254900@t31g2000cwb.googlegroups.com> References: <1143554931.104392.187480@i39g2000cwa.googlegroups.com> <1143556185.348035.254900@t31g2000cwb.googlegroups.com> Message-ID: Sathyaish wrote: >> But what's got that to do with it? Strings are very mutable in C. > > I realized after posting that I'd said something incorrect again. The > concept of "mutability" itself is a high-level concept compared to C. > Memory allocation for strings is expensive because of the way malloc() > works to find a "best-fit" against a "first-fit" in traditional memory > management systems. Because of the performance hit, high level > languages and frameworks, such as the Common Type System of the .NET > Framework for example, considers strings as immutable. That, unlike > Python, doesn't however, make them impossible to modify in-place. > I believe part of the reason for their immutability is so that they can be used as dictionary keys, which is a very common use. From nicola.musatti at gmail.com Tue Mar 7 08:17:11 2006 From: nicola.musatti at gmail.com (Nicola Musatti) Date: 7 Mar 2006 05:17:11 -0800 Subject: New python.org website In-Reply-To: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> References: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> Message-ID: <1141737431.437281.178860@z34g2000cwc.googlegroups.com> Phoe6 wrote: > beta.python.org evolved very nice and noticed today the new python.org > website going live. There is a change in the look n feel, wherein it > looks "more official" and maximum possible information about python is > now directly accessible from the home page itself. Kudoes to the > design team. Sigh! Another of these sites that all look the same, with two screenfuls of info on the home page that are going to be in the way of every returning user... Not to mention the dull color scheme and the unremarkable logo. I can't say I'm impressed. Cheers, Nicola Musatti From anon at nowhere.com Wed Mar 29 19:57:35 2006 From: anon at nowhere.com (Adam) Date: Thu, 30 Mar 2006 12:57:35 +1200 Subject: Content Management System References: <1143627824.174540.13710@z34g2000cwc.googlegroups.com> Message-ID: On Wed, 29 Mar 2006 16:32:39 GMT, Adrienne Boswell wrote: >Gazing into my crystal ball I observed "Water Cooler v2" > writing in news:1143627824.174540.13710 >@z34g2000cwc.googlegroups.com: > >> I know what it is, and yet the knowledge of what a CMS is, is so vague >> that I find myself asking this question every now and then. I've >> googled and read the resources too. However, the knowledge is still not >> clear. It is so vague. >> >> > >For me, it was a way to give my client (local parish) some things: >1. An easy way for them to make _content_ changes to their website, >without getting into the nuts and bolts and potentially creating havoc. >2. A way to make the site searchable for the user. >3. A way from keeping them from publishing Word documents as HTML - urgh! >4. A way to have content changes immediate, and not have to wait for 24 >hours before their current hosting company downloads content (in Word, >with no navigation). > >I rolled my own in ASP/Access, not very complicated because I didn't need >anything complicated. Try taking a look at Joomla: http://www.joomla.org/ I generally hand code PHP sites, but occasionally use a CMS. Of all the ones I tested, Joomla seemed (to me) to be the most flexible. If you install the JCE (WYSIWYG) editor, it actually has a "paste from Word" function that tries to strip out as much MX cr*p as it can - but it's a tall order! I've [even] used Joomla for pretty simple non-"blog" sites simply for the remote admin and the search functions. It really is best suited for the more "newsy" community sites. It's definitely worth a look at, IMHO. Adam. From marek.rocki at wp.pl Fri Mar 17 16:45:26 2006 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: 17 Mar 2006 13:45:26 -0800 Subject: Linear regression in NumPy In-Reply-To: <1142628938.982098.239850@u72g2000cwu.googlegroups.com> References: <1142628938.982098.239850@u72g2000cwu.googlegroups.com> Message-ID: <1142631926.353064.206010@p10g2000cwp.googlegroups.com> nikie napisal(a): > I'm a little bit stuck with NumPy here, and neither the docs nor > trial&error seems to lead me anywhere: > I've got a set of data points (x/y-coordinates) and want to fit a > straight line through them, using LMSE linear regression. Simple > enough. I thought instead of looking up the formulas I'd just see if > there isn't a NumPy function that does exactly this. What I found was > "linear_least_squares", but I can't figure out what kind of parameters > it expects: I tried passing it my array of X-coordinates and the array > of Y-coordinates, but it complains that the first parameter should be > two-dimensional. But well, my data is 1d. I guess I could pack the X/Y > coordinates into one 2d-array, but then, what do I do with the second > parameter? Well, it works for me: x = Matrix([[1, 1], [1, 2], [1, 3]]) y = Matrix([[1], [2], [4]]) print linear_least_squares(x, y) Make sure the dimensions are right. X should be n*k, Y should (unless you know what you are doing) be n*1. So the first dimension must be equal. If you wanted to: y = Matrix([1, 2, 4]) it won't work because it'll have dimensions 1*3. You would have to transpose it: y = transpose(Matrix([1, 2, 4])) Hope this helps. From aleaxit at yahoo.com Sat Mar 18 21:04:49 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 18 Mar 2006 18:04:49 -0800 Subject: can't rebind magic methods References: <1142727958.529520.302980@j33g2000cwa.googlegroups.com> Message-ID: <1hceppf.1smucdv4fkudsN%aleaxit@yahoo.com> Michael Tobis wrote: > I'd appreciate an explanation of why this doesn't work and any > workarounds. Special methods are looked up (for their automatic use) on the type, not the instance. The workaround is therefore to set them on the type, too: > class myint(object): > > def __init__(self,val): > self.val = int(val) > def mystr(self): > return self.val.__str__() > self.__str__ = new.instancemethod(mystr,self,mint) #doesn't > work What you need is to have *** as myint.__str__ *** the method you want to get called. If you have a bunch of special methods that you want to ensure delegate to self.val.(samemethod), you don't have to write them out -- you can assign them as attributes of myint, with a simple loop of setattr right after the class statement, or with a custom metaclass, or whatever you find handiest. For example (warning, untested code): def _setdelegate(cls, delegate_cls, name): method = getattr(delegate_cls, name) def f(self, *a, **k): return method(self.val, *a, **k) f.func_name = name setattr(cls, name, f) class myint(object): def __init__(self, val): self.val = int(val) for spec in 'str repr hash hex oct'.split(): _setdelegate(myint, '__%s__' % spec) This may be worth refactoring into a custom metaclass if you need more than one class like this myint, but that's quite a side issue. Alex From peter at engcorp.com Mon Mar 27 08:07:01 2006 From: peter at engcorp.com (Peter Hansen) Date: Mon, 27 Mar 2006 08:07:01 -0500 Subject: Difference between 'is' and '==' In-Reply-To: References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <4427d287$0$38669$edfadb0f@dread12.news.tele.dk> Message-ID: Roy Smith wrote: > In article , > Joel Hedlund wrote: >>Which means that "is" comparisons in general will be faster than == >>comparisons. > > I thought that == automatically compared identify before trying to compare > the values. Or am I thinking of some special case, like strings? You must be thinking of a special case: >>> class A: ... def __cmp__(self, other): return 1 ... >>> a = A() >>> a is a True >>> a == a False -Peter From and-google at doxdesk.com Mon Mar 20 11:56:59 2006 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 20 Mar 2006 08:56:59 -0800 Subject: New-style Python icons Message-ID: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> Personally, I *like* the new website look, and I'm glad to see Python having a proper logo at last! I've taken the opportunity to knock up some icons using it, finally banishing the poor old standard-VGA-palette snake from my desktop. If you like, you can grab them from: http://www.doxdesk.com/img/software/py/icons.zip in .ICO format for Windows - containing all resolutions/depths up to and including Windows Vista's crazy new enormo-icons. Also contains the vector graphics source file in Xara format. You can also see a preview here: http://www.doxdesk.com/img/software/py/icons.png -- And Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From simon at brunningonline.net Thu Mar 2 13:55:57 2006 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 2 Mar 2006 18:55:57 +0000 Subject: Simple System Tray Icon In-Reply-To: References: Message-ID: <8c7f10c60603021055xb84ea1fu75ec53dd4850bd9d@mail.gmail.com> On 3/2/06, 3c273 wrote: > I guess I should have capitalized the word 'simple' in my request :-) Thanks > for your reply. I had already found this and it made the wx example look > like a one-liner. I didn't realize that this was such a chore. Thanks again, > I will keep trying. > Louis This is untested, 'cos I'm on a Mac these days, but what you want should look something like: from SysTrayIcon import SysTrayIcon icon = SysTrayIcon('parh/to/icon.ico', "Hover text", {}) How simple do you want? -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From michaeltaft at gmail.com Fri Mar 17 13:57:48 2006 From: michaeltaft at gmail.com (mwt) Date: 17 Mar 2006 10:57:48 -0800 Subject: Parsing Hints Message-ID: <1142621868.352146.242430@j33g2000cwa.googlegroups.com> Hi - I'm working on parsing a file that has data that looks like the sample below. Obviously, I can't just split the string by colons. I'm pretty new to regex, but I was thinking of something that would essentially "split" by colons only if the are preceded by alpha characters -- thus eliminating problems of splitting up times, etc. Still, I'm nagged by the spectre of you gurus knowing a powerful way to approach this problem. Am I on the right track here with this regex idea? Any hints as to the sanest angle on parsing this would be appreciated. Thanks. Here's a sample of the data: Index 4: folding now server: 171.65.199.158:8080; project: 1809 Folding: run 17, clone 19, generation 35; benchmark 669; misc: 500, 400 issue: Wed Mar 15 18:32:19 2006; begin: Wed Mar 15 18:32:25 2006 due: Fri Apr 28 19:32:25 2006 (44 days) core URL: http://www.stanford.edu/~pande/Linux/x86/Core_82.fah CPU: 1,0 x86; OS: 4,0 Linux assignment info (le): Wed Mar 15 18:32:19 2006; A0F3AAD2 CS: 171.65.103.100; P limit: 5241856 user: MWT; team: 0; ID: 1A2BFB777775B7B; mach ID: 2 work/wudata_04.dat file size: 82814; WU type: Folding at Home Average download rate 97.552 KB/s (u=4); upload rate 38.718 KB/s (u=3) Performance fraction 0.950453 (u=3) From sudharsh at gmail.com Sat Mar 18 09:15:54 2006 From: sudharsh at gmail.com (sudharsh at gmail.com) Date: 18 Mar 2006 06:15:54 -0800 Subject: Writing web bots in python In-Reply-To: <1142672307.115277.203150@p10g2000cwp.googlegroups.com> References: <1142668903.336769.184570@u72g2000cwu.googlegroups.com> <1142672307.115277.203150@p10g2000cwp.googlegroups.com> Message-ID: <1142691354.403025.13120@z34g2000cwc.googlegroups.com> Thanx for the info..i'll let you know when it works From steve at REMOVETHIScyber.com.au Sun Mar 5 12:05:04 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 06 Mar 2006 04:05:04 +1100 Subject: raw strings and \ References: <1141548565.145199.145910@e56g2000cwe.googlegroups.com> <1141576051.081203.318010@e56g2000cwe.googlegroups.com> Message-ID: On Sun, 05 Mar 2006 08:27:31 -0800, plahey wrote: > Hi Duncan, > > thanks for the reply. I figured that this was a technical problem > associated with the parser. > > This one is going on my Python gotchas list. It is really silly from > an end user perspective to have \ not special in raw strings _except_ > if it is the last character. I don't deny that this is a gotcha, but you misunderstand the purpose of raw strings. They weren't designed so that Windows users could enter pathnames with backslashes. Raw strings are designed to enter regular expressions, and for regular expressions, not being able to end a string with a backslash is not a bug but a feature. See http://www.ferg.org/projects/python_gotchas.html#contents_item_2 (and try not to choke on the oh-so-saccharine-sweet cutesy introduction. Red Ridinghood indeed *wink*) -- Steven. From luis_lupe2XXX at netvisaoXXX.pt Sat Mar 4 11:20:16 2006 From: luis_lupe2XXX at netvisaoXXX.pt (Luis P. Mendes) Date: Sat, 04 Mar 2006 16:20:16 +0000 Subject: socket freezes In-Reply-To: References: <46qtqqFcej8bU1@individual.net> <46rm84Fcet0eU1@individual.net> Message-ID: <46tt0uFcv9lbU1@individual.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Thank you all for your suggestions. Luis P. Mendes -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFECb5AHn4UHCY8rB8RAmeLAKCmSVfTvgQ94NPnJlD2QqdbMwVFXACdGFAh 8GL/9zxwXCYcmWxpyDweggE= =9U0o -----END PGP SIGNATURE----- From joel.hedlund at gmail.com Tue Mar 21 05:31:37 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Tue, 21 Mar 2006 11:31:37 +0100 Subject: New-style Python icons In-Reply-To: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> Message-ID: > http://www.doxdesk.com/img/software/py/icons.png Neat! /Joel Hedlund From lycka at carmen.se Thu Mar 9 14:21:59 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 09 Mar 2006 20:21:59 +0100 Subject: Python Evangelism In-Reply-To: References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> Message-ID: rtilley wrote: > Steve Holden wrote: > >> Doug Bromley wrote: >> >>> I can see Ruby overtaking Python if we don't ALL do something about it. > > > I think it's the name. Python. Let's change it to something nicer. Think > about it... if you found a Ruby, you'd pick it up and put it in your > pocket. If you ran across a Python, you'd run away. I think you have a point, but I also think it's a bit late to change it after 15 years or so, considering all books, web sites etc. We're stuck with Python, and can only do the best of that. Actually, in Swedish, "Jag m?r pyton" i.e. "I feel like python" means "I feel sick", and "det luktar pyton" i.e. "it smells python", means "it stinks". That doesn't make Python easier to sell here... Still to late to change... It's not too late to rename the cheese shop though. (We don't need even more stink...) I think a good example on the problem with letting techies like us do naming is that grand successor of Unix developed by the great minds at Bell Labs. First, they name it after a movie which is famous for being exceptionally bad--Plan 9 (from outer space). Really grand company there! Then, when they make a real product of it, they call it Inferno, and some part of it gets called Limbo. They do this on purpose in the U.S. A country full of religious fanatics, where it's impossible to be elected president unless you claim that you are a devoted Christian and say "God bless America" every time you open your mouth. No wonder the preferred operating systems (except a boring proprietary one) are still purely old fashion Unix based ones. Most of those smart improvements never quite made it... From paul at boddie.org.uk Fri Mar 31 19:14:34 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 31 Mar 2006 16:14:34 -0800 Subject: Doc suggestions (was: Why "class exceptions" are not deprecated?) References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com> <1143574346.354680.136060@i39g2000cwa.googlegroups.com> <1143765024.109931.96090@j33g2000cwa.googlegroups.com> <1143842010.610324.16710@t31g2000cwb.googlegroups.com> Message-ID: <1143850474.174268.301670@t31g2000cwb.googlegroups.com> rurpy at yahoo.com wrote: > Ed Singleton wrote: > > > > Ideas can come from anyone and they do come from anyone all the time, > > and as such they are fairly worthless unless acted upon. > > That is pretty obvious. The question is about who does > the acting. Your position seems to be that > only those that act have a right to present ideas. This > is bogus for a whole bunch of reasons: At this point, I have to say that this post reveals a pretty good insight into the nature of community dynamics. > - It is exceptional case when people go off and do something > by themselves and produce good results. The power of > free software lies in its collaborative nature. Indeed. Which is why it can be puzzling sometimes to see certain communities and movements put all their money on one horse, to use a common analogy. People should feel encouraged to do offbeat or tangential stuff, especially if it costs the other people nothing more than an act of encouragement. > - Many changes are too big or pervasive, and need > cooperation from many people (or at least agreement.) > - Even small changes often need help from others > (sometimes just information) > - People can have a good idea, even if they are not capable > of implementing it. And consider a combination of these factors: there are several different resources for proposing amendments to the Python documentation; to make a standard replacement for the documentation, you need consensus; to make a better replacement, you either need people to use your resource to propose improvements, or you need to be able to collaborate with all the other resources/mechanisms, and thus you need standardisation. No-one has all the technical, social and political answers, nor should they be asked to come up with them all. Having people proposing changes to the documentation and having tools available to make such changes convenient both solve important issues, but various social and political issues remain. If we ignore these potentially unsolved issues, though, noting that Fredrik and others have provided technical solutions, it'd probably be for the best if those people perceived to be complaining were just encouraged to use such solutions rather than being made to feel stupid because they don't have the technical abilities to solve that one aspect of the wider problem. > - This is particularly true in documentation and ui where > the lowly user is, in many respects, the expert. > - Even if an idea is not good, it can start someone else > thinking and their idea may be good. Indeed. People who don't feel able to contribute to one part of a solution shouldn't be discouraged from contributing where they can. Perhaps it has been difficult to field documentation updates within the current workflow, and perhaps it is more productive for the maintainers to not encourage certain levels or kinds of suggestions or improvements since they would end up with a lot of editing and administrative work, but the technical impediments are not the fault of those willing to contribute - if people lose sight of that, then... > - Without outside ideas and critisism the core > development group can become "inbred" and loose touch > with the user community. Well, there was the "smug" label brought up some time ago. I'd argue that certain parts of the community could subsequently be labelled as "rattled" due to certain arguable trends in technology adoption, and perhaps the python.org redesign brought all this to the fore. And on that subject, perhaps I'd better get back to looking at that particular set of tools... Paul From grante at visi.com Mon Mar 27 11:04:25 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 27 Mar 2006 16:04:25 -0000 Subject: encode short string as filename (unix/windows) References: Message-ID: <122g389g33019c@corp.supernews.com> On 2006-03-27, robert wrote: > want to encode/decode an arbitrary short 8-bit string as save filename. > is there a good already builtin encoding to do this (without too much > inflation) ? or re.sub expression? > > or which characters are not allowed in filenames on typical OS? Under unix, "/" and NULL aer not allowed. There are other characters that are not recommended, but those are the only two that are not allowed. -- Grant Edwards grante Yow! .. the MYSTERIANS are at in here with my CORDUROY visi.com SOAP DISH!! From no-spam at no-spam-no-spam.com Thu Mar 2 10:56:45 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 02 Mar 2006 16:56:45 +0100 Subject: os.popen3 delivers no error exist status ? Message-ID: os.popen3 delivers no error exit status on .close() - while os.popen does Is this intended or a bug? How do I get the status? Robert Python 2.4.1 (#2, May 5 2005, 11:32:06) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> csi,cso,cse=os.popen3('recodex latin1:utf8 >> csi.close();cso.read();cso.close();cse.read();cso.close() '' '/bin/sh: line 1: text.lat1-noexist.txt: No such file or directory\n' >>> cso=os.popen('recode latin1:utf8 >> sh: line 1: text.lat1-noexist.txt: No such file or directory >>> cso.read();cso.close() '' 256 >>> From walter at livinglogic.de Wed Mar 1 10:44:31 2006 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Wed, 01 Mar 2006 16:44:31 +0100 Subject: unicode question In-Reply-To: <44037105.1030100@gradient.cis.upenn.edu> References: <43FFC95E.4030202@gradient.cis.upenn.edu> <440334D3.5010302@livinglogic.de> <44037105.1030100@gradient.cis.upenn.edu> Message-ID: <4405C15F.5040806@livinglogic.de> Edward Loper wrote: > Walter D?rwald wrote: >> Edward Loper wrote: >> >>> [...] >>> Surely there's a better way than converting back and forth 3 times? Is >>> there a reason that the 'backslashreplace' error mode can't be used >>> with codecs.decode? >>> >>> >>> 'abc \xff\xe8 def'.decode('ascii', 'backslashreplace') >>> Traceback (most recent call last): >>> File "", line 1, in ? >>> TypeError: don't know how to handle UnicodeDecodeError in error callback >> >> The backslashreplace error handler is an *error* *handler*, i.e. it >> gives you a replacement text if an input character can't be encoded. >> But a backslash character in an 8bit string is no error, so it won't >> get replaced on decoding. > > I'm not sure I follow exactly -- the input string I gave as an example > did not contain any backslash characters. Unless by "backslash > character" you mean a character c such that ord(c)>127. I guess it > depends on which class of errors you think the error handler should be > handling. :) The codec system's pretty complex, so I'm willing to > accept on faith that there may be a good reason to have error handlers > only make replacements in the encode direction, and not in the decode > direction. Both directions are completely non-symmetric. On encoding an error can only happen when the character is unencodable (e.g. for charmap codecs anything outside the set of 256 characters). On decoding an error means that the byte stream violates the internal format of the encoding. But a 0x5c byte (i.e. a backslash) in e.g. a latin-1 byte sequence doesn't violate the internal format of the latin-1 encoding (nothing does), so the error handler never kicks in. >> What you want is a different codec (try e.g. "string-escape" or >> "unicode-escape"). > > This is very close, but unfortunately won't quite work for my purposes, > because it also puts backslashes before "'" and "\\" and maybe a few > other characters. :-/ OK, seems you're stuck with your decode/encode/decode call. > >>> print "test: '\xff'".encode('string-escape').decode('ascii') > test: \'\xff\' > > >>> print do_what_i_want("test:\xff'") > test: '\xff' > > I think I'll just have to stick with rolling my own. Bye, Walter D?rwald From jjl at pobox.com Sat Mar 25 18:22:58 2006 From: jjl at pobox.com (John J. Lee) Date: 25 Mar 2006 23:22:58 +0000 Subject: __slots__ References: <1143106365.996810.269780@z34g2000cwc.googlegroups.com> <1hcqwk5.9z7uv51pwbdrbN%aleaxit@yahoo.com> <1hcr1bw.1dywgpk1l0cpafN%aleaxit@yahoo.com> Message-ID: <87mzfeaz3h.fsf@pobox.com> aleaxit at yahoo.com (Alex Martelli) writes: [...] > you should be using pychecker or pylint [...] I'm curious, as somebody who doesn't regularly use these tools: How do they fit into your workflow? Do you run them every few hours, every day, every time you run functional tests, every release, every so often, on gut feeling about when it's likely to catch problems...? How do you cope with spurious warnings? Does it involve tweaking code to quell warnings? Keeping suppression lists? Maintaining special invocations of pychecker / pylint per-project? Do they cope well with other people's code who do not use these tools? John From sjuranic at gmail.com Wed Mar 29 09:45:24 2006 From: sjuranic at gmail.com (Steve Juranich) Date: Wed, 29 Mar 2006 07:45:24 -0700 Subject: Parsing csh scripts with python References: <4429B111.2020806@ilm.com> Message-ID: David Hirschfield wrote: > Is there a module out there that would be able to parse a csh script and > give me back a parse tree? > > I need to be able to parse the script, modify some variable settings and > then write the script back out so that the only changes are the > variables I've modified (comments, ordering of statements, etc. must > remain the same). > > I looked at shlex, but I don't think it will do what I need. > Any suggestions would be appreciated, > -Dave There are a number of lexical scanners available for Python, but given your problem description, that's probably not what you want. I'd just process the each line, either making modifications or not, then put the processed line on an "out" buffer (list of strings), then write that list to a file. If you do it right, all the comments and things will remain in place. -- Steve Juranich Tucson, AZ USA From reinhold.strobl at gmail.com Thu Mar 16 01:50:40 2006 From: reinhold.strobl at gmail.com (reinsn) Date: 15 Mar 2006 22:50:40 -0800 Subject: Other languages for PVM Message-ID: <1142491840.639326.254640@p10g2000cwp.googlegroups.com> Hi, I am cuurently working with Python and the PVM. I found that there is something interesting like Jython, which allows to compile python source code in *.class file. What I am looking for, are languages for the Python Virtual Machine, which means, languages that could be compiled to the Python byte code. Thanks a lot in advance! From trepca at gmail.com Fri Mar 3 06:54:39 2006 From: trepca at gmail.com (Sebastjan Trepca) Date: Fri, 3 Mar 2006 12:54:39 +0100 Subject: encoding problem In-Reply-To: <440827D6.3060501@sitasoftware.lu> References: <440827D6.3060501@sitasoftware.lu> Message-ID: I think you are trying to concatenate a unicode string with regular one so when it tries to convert the regular string to unicode with ASCII(default one) encoding it fails. First find out which of these strings is regular and how it was encoded, then you can decode it like this(if regular string is diff): mailbody +=diff.decode('') Sebastjan On 3/3/06, Yves Glodt wrote: > Hi list, > > > Playing with the great pysvn I get this problem: > > > Traceback (most recent call last): > File "D:\avn\mail.py", line 80, in ? > mailbody += diff > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position > 10710: ordinal not in range(128) > > > > It seems the pysvn.client.diff function returns "bytes" (as I read in > the changelog of pysvn: http://svn.haxx.se/dev/archive-2005-10/0466.shtml) > > How can I convert this string so that I can contatenate it to my > "regular" string? > > > Best regards, > Yves > -- > http://mail.python.org/mailman/listinfo/python-list > From steven.bethard at gmail.com Thu Mar 23 11:24:38 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 23 Mar 2006 09:24:38 -0700 Subject: Per instance descriptors ? In-Reply-To: <44226a82$0$20833$636a55ce@news.free.fr> References: <44211ee8$0$7890$636a55ce@news.free.fr> <44226a82$0$20833$636a55ce@news.free.fr> Message-ID: bruno at modulix wrote: > Steven Bethard wrote: >> Could you explain again why you don't want baaz to be a class-level >> attribute? > > Because the class is a decorator for many controller functions, and each > controller function will need it's own set of descriptors, so I don't > want to mess with the class. So you're trying to add property-like attributes to functions? That is, you want something like: @my_decorator def f(...): ... f.foo # calls f._get_foo() in another post, bruno at modulix wrote: > This would imply a decorator subclass and a descriptor subclass for > each and every controller function - which is what I'm trying to > avoid. So you only want one decorator? Doesn't that mean that all functions will have the same attributes? But if that were true you would only need one descriptor for all controller functions, so I must not be understanding that right. Can you give a little more realistic code sample? I'm still not sure what it is you really want to do. Don't worry about showing the implementation you're thinking of. Just show me how you want to use these things and what it ought to look like. STeVe From eric_brunel at despammed.com Fri Mar 31 02:56:48 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 31 Mar 2006 09:56:48 +0200 Subject: tkinter question References: <1143501305.697282.283180@t31g2000cwb.googlegroups.com> <1143670082.175804.317850@t31g2000cwb.googlegroups.com> <1143760279.774693.61460@j33g2000cwa.googlegroups.com> Message-ID: On 30 Mar 2006 15:11:19 -0800, wrote: >> If you just create >> a Toplevel and populate it with widgets, it will just display once the >> control is returned to the Tkinter mainloop and no user input will be >> needed. > > Thanks for explaining that. I borrowed the "after" method that you used > in your first reply. It seems to do what I want (except for > root.destroy) Though any suggestions on a more elegant solution > welcome. > > cheers David [snip start of code] > def goodbye(): > print "step 4 you are logged out" > root.destroy This is not a method call. To do what you want, write: root.destroy() Methods are first class objects in Python, so root.destroy is just the method object for the destroy method applied to root. Written like that, it just gets the object, but does not call it. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From vbgunz at gmail.com Fri Mar 17 14:44:20 2006 From: vbgunz at gmail.com (vbgunz) Date: 17 Mar 2006 11:44:20 -0800 Subject: My Generator Paradox! In-Reply-To: References: <1142554666.740989.303350@p10g2000cwp.googlegroups.com> Message-ID: <1142624660.080497.51720@v46g2000cwv.googlegroups.com> I believe I understand now. the yield keyword is sort of like a cousin to return. return will bring back an object I can work with and so does yield *but* yield's object will most likely support the .next() method. So, if I worked with a function that ends with the return keyword and it returns a list, I can run list operations and list methods on it. if a function ends with the yield keyword a generator should return. So, calling the function by it's name will always reset and initialize the generator. Whereas assigning to the functions yielded return grants access to the real generator in which I can use the next() method. Maybe I've explained it wrong *but* it does make sense to me now. I just couldn't grasp it because I am still new to the keyword yield and didn't know it sort of works like return. I really wish to thank you fellas so much for your examples and explanations! I think I got it! I thank you all again! From ramen at lackingtalent.com Thu Mar 2 16:48:07 2006 From: ramen at lackingtalent.com (Dave Benjamin) Date: Thu, 2 Mar 2006 15:48:07 -0600 Subject: import, from and reload In-Reply-To: References: Message-ID: On Thu, 2 Mar 2006, John Salerno wrote: > Dave Benjamin wrote: > >> In general, "from X import *" should be avoided anyway, for reasons that >> have been discussed many times in the past. The annoyance with reloading is >> just one more reason. Better to just use "import X" in the first place. > > Thanks. I kind of figured it's better to use import instead of from anyway, > but I was following along with some examples that use from (despite the fact > that earlier in the book they even say that from is problematic and you > should use import instead!) :) No problem. I stand by my original advice, but there is one semi-oneliner that you might find useful: reload(__import__('X')); from X import * You could keep that in your clipboard and paste it into the interpreter when you need to reload. -- .:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:. "one man's constant is another man's variable" - alan perlis From jordan.taylor2 at gmail.com Fri Mar 3 22:10:45 2006 From: jordan.taylor2 at gmail.com (jordan.taylor2 at gmail.com) Date: 3 Mar 2006 19:10:45 -0800 Subject: Win32api, pyHook, possibly win32com, not sure XD, thats why I'm posting In-Reply-To: References: <1141435919.954008.241240@t39g2000cwt.googlegroups.com> Message-ID: <1141441845.098430.320780@e56g2000cwe.googlegroups.com> I'm really trying to figure out the overall extent with which python can interact with the windows system (curious person ;D). I can't seem to find documentation on it, so if anyone could point me to that... i know python can kill processes and return what processes are running, so i was just wondering if it could hide them as well. From sybrenUSE at YOURthirdtower.com.imagination Thu Mar 23 10:29:20 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 23 Mar 2006 16:29:20 +0100 Subject: Default/editable string to raw_input References: Message-ID: Sion Arrowsmith enlightened us with: > You're assuming that the tester is already familiar with a text > editor. Indeed. Someone working on a test suite sounded like someone who knows how to work with a text editor. > And then they would have to learn the syntax of the configuration > file, and the parameters available. True. Thorough comments and a clear syntax help a long way. > A point-and-drool interface requires no such learning. But that's not what you get with raw_input(). 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 fumanchu at amor.org Mon Mar 13 01:36:59 2006 From: fumanchu at amor.org (fumanchu) Date: 12 Mar 2006 22:36:59 -0800 Subject: "RuntimeError: dictionary changed size during iteration" ; Good atomic copy operations? References: <1142214997.549342.123440@e56g2000cwe.googlegroups.com> Message-ID: <1142231819.707289.96610@u72g2000cwu.googlegroups.com> You can also *almost* do it with a tracehook that blocks until released by another thread. See http://projects.amor.org/misc/wiki/PyConquer for the tool I'm sporadically working on that does that (in an effort to test all possible execution paths). The only limitation is that trace functions aren't called on every bytecode. Robert Brewer System Architect Amor Ministries fumanchu at amor.org From R.Brodie at rl.ac.uk Thu Mar 30 08:21:27 2006 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 30 Mar 2006 14:21:27 +0100 Subject: does python could support sequence of short or int? References: <1143703009.628171.203020@i39g2000cwa.googlegroups.com> <1143715011.981884.136560@j33g2000cwa.googlegroups.com> <1143722234.988260.201690@t31g2000cwb.googlegroups.com> Message-ID: "momobear" wrote in message news:1143722234.988260.201690 at t31g2000cwb.googlegroups.com... > then how can I convert it to a int list? I read about struct and array, > I think they are not suitable, since I don't know how long will the > buffer is. I know if I write a plugins modules in C should works, but > that's really upset to tell to myself there is no way in Python. I'm not sure why you think that the array and struct modules are unsuitable: >>>import array >>>buffer = 'iidfkljkkkkhfpa3' >>>arr = array.array('h', buffer) >>> print arr array('h', [26985, 26212, 27755, 27498, 27499, 26731, 28774, 13153]) From max at alcyone.com Fri Mar 24 01:01:57 2006 From: max at alcyone.com (Erik Max Francis) Date: Thu, 23 Mar 2006 22:01:57 -0800 Subject: Strings and % sign fails - Help Please In-Reply-To: <87odzwpfgs.fsf@ieee.org> References: <1143168531.461348.130160@t31g2000cwb.googlegroups.com> <87lkv0r1lk.fsf@ieee.org> <1143169736.507783.95460@z34g2000cwc.googlegroups.com> <87d5gcr0ng.fsf@ieee.org> <87odzwpfgs.fsf@ieee.org> Message-ID: Jorge Godoy wrote: > I know. I'm just trying to see if there might be some magic going on with his > driver... Since raw strings have no effect on format specifiers, that won't tell you anything. >>> r'%' == '%' True His problem is that cursor.execute does format expansion with %, so a single % is not legal. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis We are victims of our circumstance. -- Sade Adu From dabbaking at gmail.com Sat Mar 18 17:41:56 2006 From: dabbaking at gmail.com (Dave) Date: 18 Mar 2006 14:41:56 -0800 Subject: Getting .NET SDK to work with Python 2.4.2 Message-ID: <1142721716.734835.157980@z34g2000cwc.googlegroups.com> I searched the usenet and some mail archives and tried various techniques, but I can't seem to get the .NET 2.0 SDK to work with python. I'm a total newbie when it comes to python installs. I downloaded the .NET 2.0 SDK and I have python 2.4.2 and im trying to install zope. So i go to the cmd and go to the directory and type "python setup.py build" (Will have to install after) and it comes up with this(after everything else runs smoothly): running build_ext error: The .NET SDK needs to be installed before building extensions for python. I set the .net2.0 directory in windows enviromental PATH and added a key to registry in: HKEY_{LOCAL_MACHINE}\Software\Microsoft\.NETFramework\FrameworkSDKDir to the path of it. It still doesn't recongnize it and I don't know why. From weekender_ny at yahoo.com Sun Mar 5 11:36:22 2006 From: weekender_ny at yahoo.com (John) Date: 5 Mar 2006 08:36:22 -0800 Subject: testing for existence of compilers/executables Message-ID: <1141576582.569566.173120@v46g2000cwv.googlegroups.com> I am working with my build system using scons. I would like to test the existence of 'doxygen' or any other compiler/executable in the path (like gcc/icc/...) What is the most efficient way to find this out using python? using scons? Is there a way to list all C/C++/fortran compilers available on a machine using python so that I can give my user an option to select one? Thanks a lot for your help, --j From Ido.Yehieli at gmail.com Mon Mar 20 12:07:26 2006 From: Ido.Yehieli at gmail.com (Ido Yehieli) Date: 20 Mar 2006 09:07:26 -0800 Subject: Python / glade fundamentals In-Reply-To: <441edd77$0$10782$79c14f64@nan-newsreader-07.noos.net> References: <1142604240.110403.110560@v46g2000cwv.googlegroups.com> <441edd77$0$10782$79c14f64@nan-newsreader-07.noos.net> Message-ID: <1142874446.482939.22310@i40g2000cwc.googlegroups.com> Franck: PyGG seems pretty cool, thanks for the link! From erniedude at gmail.com Tue Mar 7 14:48:36 2006 From: erniedude at gmail.com (Ernesto) Date: 7 Mar 2006 11:48:36 -0800 Subject: Send email notification In-Reply-To: References: <1141759889.952367.59260@j33g2000cwa.googlegroups.com> Message-ID: <1141760916.715817.3800@i40g2000cwc.googlegroups.com> I guess that was jerk-off version of: "smtplib" Thanks a lot. From nessus at mit.edu Tue Mar 7 18:59:30 2006 From: nessus at mit.edu (Douglas Alan) Date: Tue, 07 Mar 2006 18:59:30 -0500 Subject: Any advantage in LISPs having simpler grammars than Python? References: <1141770067.041526.292360@p10g2000cwp.googlegroups.com> Message-ID: Terry Hancock writes: > I think experienced Lisp programmers must learn to visually parse > the *words* in the Lisp program to determine the structure, but I > find that really unhelpful, myself. Experienced Lisp programmers use indentation to visually parse the program structure, just like Python programmers do for Python. Experienced Lisp programmers learn to not see the parentheses when they don't need to. When I did a lot of Lisp programming, I often felt that it would be kind of nice to have a version of Lisp that would infer many of the parentheses from indentation, so that you could elide most of them. But then again, the parentheses are very easy for an experienced Lisp programmer to ignore, so such a change would have been a very hard sell. |>oug From russandheather at gmail.com Tue Mar 28 12:03:03 2006 From: russandheather at gmail.com (Russell Warren) Date: 28 Mar 2006 09:03:03 -0800 Subject: Seems like I want a pre-processor, but... In-Reply-To: <1143562487.421862.258860@u72g2000cwu.googlegroups.com> References: <1143562487.421862.258860@u72g2000cwu.googlegroups.com> Message-ID: <1143565383.860118.295230@t31g2000cwb.googlegroups.com> Thanks guys - all great responses that answered my question in a few different ways with the addition of some other useful tidbits! This is a nice summary: > In general the idea is to move the test from 'every time I need to do > something' to 'once when some name is defined'. Gotta love the response time of this newsgroup... Russ From __peter__ at web.de Tue Mar 14 06:44:26 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 14 Mar 2006 12:44:26 +0100 Subject: Localized month names? References: <47niphFgg5kaU1@news.dfncis.de> Message-ID: Sibylle Koczian wrote: > Benji York schrieb: >> Jarek Zgoda wrote: >> >>> How do I get a list of localized month names for current locale? The >>> first thing that came to my mind was an ugly hack: >> >> >>>>> import locale >>>>> locale.nl_langinfo(locale.MON_1) >> 'January' >> > > What did you leave out? Nothing, most likely. > I get > > Traceback (most recent call last): > File "", line 1, in -toplevel- > locale.nl_langinfo(locale.MON_1) > AttributeError: 'module' object has no attribute 'nl_langinfo' > > (Python 2.4, german Windows XP Pro) > > Moreover, 'January' is probably not localized. Python 2.4.2 (#4, Nov 19 2005, 13:25:59) [GCC 3.3.3 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import locale >>> locale.nl_langinfo(locale.MON_1) 'January' >>> locale.setlocale(locale.LC_ALL, "") 'de_DE.UTF-8' >>> locale.nl_langinfo(locale.MON_1) 'Januar' Peter From bdesth.quelquechose at free.quelquepart.fr Sun Mar 5 20:11:01 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 06 Mar 2006 02:11:01 +0100 Subject: Separating elements from a list according to preceding element In-Reply-To: <1141594969.897337.215970@v46g2000cwv.googlegroups.com> References: <1141587629.918414.245530@t39g2000cwt.googlegroups.com> <1141589424.031872.309820@j33g2000cwa.googlegroups.com> <1hbq8sw.3qtwcztds5a9N%aleaxit@yahoo.com> <1141594969.897337.215970@v46g2000cwv.googlegroups.com> Message-ID: <440b615d$0$15868$636a55ce@news.free.fr> Gerard Flanagan a ?crit : > Alex Martelli wrote: > >>Gerard Flanagan wrote: >> ... >> >>>a = [ '+', 'tag1', '+', 'tag2', '-', 'tag3', '+', 'tag4' ] >>> >>>import itertools >>> >>>b = list(itertools.islice(a,0,8,2)) >>>c = list(itertools.islice(a,1,8,2)) >> >>Much as I love itertools, this specific task would be best expressed ad >> >>b = a[::2] >>c = a[1::2] >> > > > Yes, I thought that when I saw bruno's solution - I can't say that I've > never seen that syntax before, but I never really understood that this > is what it did. It's in fact pretty simple. The full slice syntax is [start:end:step], with default values of start=0, end=len(seq), step=1. So a[::2] will retrieve a[0], a[2], a[4] etc, and a[1::2] -> a[1], a[3], a[5] etc. (snip) From timothy.soehnlin at gmail.com Sun Mar 26 09:15:06 2006 From: timothy.soehnlin at gmail.com (timothy.soehnlin at gmail.com) Date: 26 Mar 2006 06:15:06 -0800 Subject: What's The Best Editor for python In-Reply-To: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> References: <1143218563.733352.26960@g10g2000cwb.googlegroups.com> Message-ID: <1143382506.897929.175210@v46g2000cwv.googlegroups.com> For myself, I use kdevelop, KDE's development environment, it handles a multitude of languages very well, and python is one of them. It has solid project management, and a slew of other features. If you are looking for something solid, I would go with kdevelop. From felipe.lessa at gmail.com Mon Mar 27 22:12:15 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 28 Mar 2006 00:12:15 -0300 Subject: Difference between 'is' and '==' In-Reply-To: References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <4427d287$0$38669$edfadb0f@dread12.news.tele.dk> Message-ID: <1143515536.4490.44.camel@kenshin> Em Seg, 2006-03-27 ?s 21:05 -0500, Dan Sommers escreveu: > Right off the top of my head, I can't think of a way to make "a = b; a > is b" return False. Sorry for being so --quiet. I will try to be more --verbose. I can think of two types of constants: 1) Those defined in the language, like True, None, 0 and the like. 2) Those defined on your code. You said type 1 can be used with "is", you're right: >>> a = 100 >>> a is 100 False I said type 2 can (maybe "should"?) be used with "is", and AFAICT I'm right as well: >>> b = a >>> b is a True That said, you can do thinks like: >>> import socket >>> a = socket.AF_UNIX >>> a is socket.AF_UNIX True That kind of constants can be used with "is". But if don't want to be prone to errors as I do, use "is" only when you really know for sure that you're dealing with singletons. HTH, -- Felipe. From jeannelouw at gmail.com Sun Mar 12 13:51:53 2006 From: jeannelouw at gmail.com (kalahari) Date: 12 Mar 2006 10:51:53 -0800 Subject: Class attributes newbie question (before I join a cargocult) References: <1142188575.187032.61390@v46g2000cwv.googlegroups.com> Message-ID: <1142189513.551157.218380@e56g2000cwe.googlegroups.com> def changeSex(self, newsex=""): self.mysex=newsex --->>>>> self.mysex return self.mysex def whoAmI(self): return self.name, self. sex ->>>>>> self.sex From fredrik at pythonware.com Tue Mar 21 12:53:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 21 Mar 2006 18:53:22 +0100 Subject: Installing PyExcelerator to write Excel files from Python References: <1142963278.278651.99160@t31g2000cwb.googlegroups.com> Message-ID: tkpmep at hotmail.com wrote: > I downloaded PyExcelerator.zip as I need to write some data into Excel > files, and tried unsuccessfully to install it. I unzipped the files > into C:/Python24/Lib/site-packages/PyExcelerator, and in a python > command line window typed > > >>>os.chdir("C:/Python24/Lib/site-packages/PyExcelerator") > > followed by > > >>>python ./setup.py install > > exactly as stated in README.txt. However all I get is a SyntaxError. > > I then tried various combinations - with and without enclosing quotes, > with and without ./, and in all cases I get a SyntaxError. Has anyone > installed this program successfully? If so, what's the magic ingredient > for a successful install? use a windows *command interpreter* window, instead of typing windows commands into a Python interpreter. (if you cannot find it in your start menu, select "run..." and run the "cmd" command). From adelagon at gmail.com Thu Mar 9 12:33:06 2006 From: adelagon at gmail.com (Alvin A. Delagon) Date: Thu, 09 Mar 2006 17:33:06 +0000 Subject: Threading.Lock() question Message-ID: <441066D2.207@gmail.com> I think I just found out my problem. How stupid of me, I should've created an instance of lock in the class Process instead of class Send. Good Heaven's python's threading rocks! I stress tested the server script having two clients sending requests on a while 1 loop without even a time.sleep() and yet it still runs! ^_^ class Process(threading.Thread): lock = threading.Lock() # Lock instance should be placed here def __init__(self,query) self.query = query threading.Thread.__init__(self) def run(self): ''' Some data processing code here ''' Process.lock.acquire() cursor.execute(query) Process.lock.release() class Send(Request__POA.Send): def push(self,query,...some args here): Process(query).start() db = MySQL().connect() cursor = db.make_cursor() From fredrik at pythonware.com Wed Mar 15 17:02:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Mar 2006 23:02:00 +0100 Subject: Need advice on reading contents of a file into memory References: <1142459357.894399.143120@v46g2000cwv.googlegroups.com> Message-ID: "vinjvinj" wrote: > f = open(someFilePath, "rb") > content = [] > for data in content.read() > content.append(data) > fullContent = "".join(content) > > Is there a more efficient way of doing this? read reads until end of file, so unless the source is something unusual, a plain fullContent = content.read() should be good enough (not that it matters much; that join will be in no-op, and the list/append overhead is marginal compared to the time required to get the data from disk) From wuwei23 at gmail.com Thu Mar 30 23:35:52 2006 From: wuwei23 at gmail.com (alex23) Date: 30 Mar 2006 20:35:52 -0800 Subject: logging producing redundant entries References: Message-ID: <1143779752.126191.90900@t31g2000cwb.googlegroups.com> Jed Parsons wrote: > My problem is that, for every event logged, the logger is producing > multiple identical entries with the timestamp the same down to the > millisecond. > import logging > # basicConfig for python 2.3 > logging.basicConfig() [...] > _logger.addHandler(_handler) I think the problem might be that basicConfig does a lot more than you seem to be aware: > basicConfig( ) : > Does basic configuration for the logging system by creating a StreamHandler with > a default Formatter and adding it to the root logger. The functions debug(), info(), > warning(), error() and critical() will call basicConfig() automatically if no handlers > are defined for the root logger. So basicConfig is creating a default handler and you're then adding another, so two entries for every event. Hope this helps. - alex23 From tim at pollenation.net Sun Mar 12 11:36:41 2006 From: tim at pollenation.net (Tim Parkin) Date: Sun, 12 Mar 2006 16:36:41 +0000 Subject: Cheese Shop: some history for the new-comers In-Reply-To: References: <44126523$0$1016$afc38c87@news.optusnet.com.au> <44141D59.6050806@pollenation.net> <4414234F.7020605@pollenation.net> Message-ID: <44144E19.6070003@pollenation.net> Fredrik Lundh wrote: > Tim Parkin wrote: > I surely hope you're not optimizing the site only for people who don't in- > tend to leave the front page... > I sureley hope you can stop being facetious.. Tim Parkin From john at totalrekall.co.uk Fri Mar 17 15:17:16 2006 From: john at totalrekall.co.uk (John Dean) Date: Fri, 17 Mar 2006 20:17:16 GMT Subject: Problem with C-API References: <441af112$0$8332$da0feed9@news.zen.co.uk> Message-ID: <441b1955$0$23282$db0fefd9@news.zen.co.uk> Hi Duncan Your version of the app works apart from this part .... .... else { PyObject *rString = PyObject_Str(result); if (rString==NULL) { Py_DECREF(result); PyErr_Print(); return; } printf( "The result is %s\n", PyString_AsString(rString)); Py_DECREF(rString); Py_DECREF(result); } } The result of the printf state is: "The result is None" result = PyRun_String("print x", Py_file_input, dict, dict); The above line of code displays the value returned from the title() function. My problem is I need to be able to cature the return value because in the real application it will be displayed in a Process Log Widget. Also the real scripts will be much longer. I have not had a problem writing Python extensions, but when it comes to embedded Python I just see how to get my code to work. Any further help would be greatly appreciated -- Best Regards John From adam.bachman at gmail.com Thu Mar 23 11:52:35 2006 From: adam.bachman at gmail.com (adam.bachman at gmail.com) Date: 23 Mar 2006 08:52:35 -0800 Subject: Confused: appending to a list In-Reply-To: <1143131513.032932.92560@j33g2000cwa.googlegroups.com> References: <1143131513.032932.92560@j33g2000cwa.googlegroups.com> Message-ID: <1143132755.118592.265680@u72g2000cwu.googlegroups.com> You're wanting it to stop when the len(list) == 4, right? The easiest way to change the logic would be to say while len(list) != 4: but that could get you into trouble later on. The problem with the len(list) < 5 expression is that the loop will run "one more time" as long as len(list) == 4 adding another item to the list giving you one more than you wanted. If you wanted, you could put your len() check inside the loop: # Start an empty list list = [] while 1: # Get a random number between 1 & 100 num = random.randint(1,100) # Make sure there are no duplicates if num not in list: # Append each number to the list list.append(num) if len(list) == 4: # Break if we've reached desired length. break print list I hope this gives you some ideas. From mtobis at gmail.com Sun Mar 5 23:17:41 2006 From: mtobis at gmail.com (Michael Tobis) Date: 5 Mar 2006 20:17:41 -0800 Subject: Python advocacy in scientific computation In-Reply-To: <1141589892.094037.18410@i40g2000cwc.googlegroups.com> References: <1139937227.379829.215090@z14g2000cwz.googlegroups.com> <1141436011.868907.292130@u72g2000cwu.googlegroups.com> <1141583453.403143.189400@i40g2000cwc.googlegroups.com> <1141589892.094037.18410@i40g2000cwc.googlegroups.com> Message-ID: <1141618661.103690.153630@u72g2000cwu.googlegroups.com> 1) indentation: I claim that this is a trivial matter. Indentation is enforced, but if you want to end all your blocks with #end, feel free. Or write a preprocessor to go from your preferred block style to python's 2) self.something tedious to look at. Again, you can somewhat work around this if you like. Just use "s" or "_" instead of "self". 3) missing 4) multithreading and parallel execution impossible This is simply false, though admittedly the MPI libraries need a little work. Mike Steder of our group is likely to release an alternative. A good way to think of Python is as a powerful extension to C. So using MPI from Python just amounts to setting up a communicator in C and wrapping the MPI calls. As for less tightly coupled threads on a single processor, Python is adept at it. I think the issues with multiple processors are much more those of a server farm than those of a computational cluster. We have been encountering no fundamental difficulty in cluster programs using Python. 5) "I don't like numpy's array slicing" ? this is unclear. It is somewhat different form Matlab's, but much more powerful. 1) pass by reference Python names are all references. The model is a little peculiar to Fortran and C people, but rather similar to the Java model. 2) matplotlib A correct install can be difficult, but once it works it rocks. ipython (a.k.a. pylab) is also a very nice work environment. 3D plots remain unavailable at present. 3) speed Speed matters less in Python than in other languages because Python plays so well with others. For many applications, NumPy is fine. Otherwise write your own C or C++ or F77; building the Python bindings is trivial. (F9* is problematic, though in fact we do some calling of F90 from Python using the Babel toolkit) 4) useful libraries yes. for your svd example see Hinsen's Scientific package. In general, Python's claim of "batteries included" applies to scientific code. mt From sybrenUSE at YOURthirdtower.com.imagination Tue Mar 28 07:02:40 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 28 Mar 2006 14:02:40 +0200 Subject: Converting Time question References: <000701c65249$d25342c0$0502a8c0@AS4L> Message-ID: Math enlightened us with: > I measure a time at racing events.this tracktime is measures in the format > hh:mm:ssDDD > where DDD = thousands of a second...like 17:14:11.769 > This format is being saved as a number of micro seconds since 1970.. > like 1,090516451769E+15 > How do I convert from the micros seconds back to time format above? Use the datetime.datetime.fromtimestamp() function, after dividing the number of milliseconds by 1000 to create seconds. 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 krypto.wizard at gmail.com Tue Mar 14 15:19:50 2006 From: krypto.wizard at gmail.com (krypto.wizard at gmail.com) Date: 14 Mar 2006 12:19:50 -0800 Subject: Python Debugger / IDE ?? In-Reply-To: <4417236d$0$7100$626a54ce@news.free.fr> References: <1142357338.313046.139060@i39g2000cwa.googlegroups.com> <4417236d$0$7100$626a54ce@news.free.fr> Message-ID: <1142367590.002643.106710@e56g2000cwe.googlegroups.com> My code has got big and it is an iterative program. I use print statements but I thought I could get something handy it would be useful to me. thanks From wrongbad at gmail.com Mon Mar 27 15:45:01 2006 From: wrongbad at gmail.com (I V) Date: 27 Mar 2006 12:45:01 -0800 Subject: CGI redirection: let us discuss it further In-Reply-To: <1143480299.024145.272600@u72g2000cwu.googlegroups.com> References: <1143480299.024145.272600@u72g2000cwu.googlegroups.com> Message-ID: <1143492301.300209.144310@z34g2000cwc.googlegroups.com> Sullivan WxPyQtKinter wrote: > 1. Are there any method (in python of course) to redirect to a web page > without causing a "Back" button trap(ie, when user click the back > button on their web browser, they are redirect to their current page, > while their hope is probably to go back to the last page they have > seen, rather than the redirection page with a "Location: url" head and > blank content.)? I guess this may vary from browser to browser, but on Mozilla at least, if your CGI script returns one of the 300 status codes, then the redirect page doesn't get added to the browser history, and so the back button works as expected. > 2. Are there any method to use relative path, rather than full absolute > URI path in "Location: url"? It is very essential for later transplant > work, e.g.,transplant a folder of cgi scripts from one web server to > another, with different URL. You don't have to use absolute URLs in a Location: header returned by a CGI script. The web server will handle relative URLs for you. See the CGI spec: http://hoohoo.ncsa.uiuc.edu/cgi/out.html From rrrn at yahoo.com Thu Mar 23 22:29:31 2006 From: rrrn at yahoo.com (Butternut squash) Date: Fri, 24 Mar 2006 03:29:31 GMT Subject: New development windows, IronPython or PythonWin References: <1143135013.513865.103820@u72g2000cwu.googlegroups.com> <1143166004.664604.207250@j33g2000cwa.googlegroups.com> Message-ID: sanxiyn at gmail.com wrote: > IronPython is currently nowhere near production quality. I would not > recommend it. But it's so cool. From doug.bromley at gmail.com Thu Mar 9 09:42:53 2006 From: doug.bromley at gmail.com (Doug Bromley) Date: Thu, 9 Mar 2006 14:42:53 +0000 Subject: Python Evangelism In-Reply-To: References: <1141901033.638339.272760@v46g2000cwv.googlegroups.com> <288425520603090251q1ffe6484y61b1d4ebe7f89d0d@mail.gmail.com> Message-ID: <288425520603090642y7db7824cy4de5365f36eb1605@mail.gmail.com> A defector! Release the hounds! Burn the scum! -------------- next part -------------- An HTML attachment was scrubbed... URL: From hancock at anansispaceworks.com Fri Mar 17 16:24:56 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 17 Mar 2006 15:24:56 -0600 Subject: No module named glade? Message-ID: <20060317152456.77e09d4d@samwise.anansi> I've run into something a little odd on my Debian-installed Python 2.3. I have deb packages "python2.3", "python-gtk2", and "python2.3-glade2" installed on this machine. Among other things, these DO give me the following (verified): /usr/lib/python2.3/site-packages/pygtk.pth /usr/lib/python2.3/site-packages/gtk-2.0 /usr/lib/python2.3/site-packages/gtk-2.0/gtk /usr/lib/python2.3/site-packages/gtk-2.0/gtk/glade.so The gtk directory has an __init__.py (fairly long one), pygtk.pth has simply "gtk-2.0" in it. Which all looks right to me. But... samwise:/usr/share/doc/python2.3-glade2/examples/glade> 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 gtk >>> import gtk.glade Traceback (most recent call last): File "", line 1, in ? ImportError: No module named glade >>> Huh? Have I missed something here? BTW, I just noticed that it does work fine if you happen to be in /usr/lib/python2.3/site-packages/gtk-2.0 so apparently it is some kind of path issue. But shouldn't it be able to find glade.so if it can find gtk? What else could be missing? (I've ruled out the things I know can go wrong, so there must be something else required -- I haven't tried to figure out gtk/__init__.py, does it do something peculiar that might get tripped up?). AFAIK, I haven't touched this installation, so whatever is going on is the result of the Debian installer (or at least I think that's true). It is the "unstable" branch, though. I hope I've provided enough information -- like I said, it looks to me like it should work now, but it doesn't. Any suggestions welcome. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From tjreedy at udel.edu Wed Mar 1 14:42:52 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 1 Mar 2006 14:42:52 -0500 Subject: Cross compile generation of .pyc from .py files... References: <1141176107.234667.93210@e56g2000cwe.googlegroups.com> <1141234081.046271.326160@i39g2000cwa.googlegroups.com> Message-ID: wrote in message news:1141234081.046271.326160 at i39g2000cwa.googlegroups.com... > ppc system. The "...has bad magic..." appears to indicate that The format of .pyc files, which are generated for greater speed of repeat runs, is considered an internal implementation detail subject to change. The exact details are generally specific to each x,y version. (For instance, byte codes are occasionally added.) So each version generally has a version-specific magic number and will only run .pyc files with the same magic number. If you get 'bad magic' from the interpreter, then you have a mismatch. If you are shipping .py files, there is no need to also ship .pyc files. Let them be generated as needed or run compileall at installation. Terry Jan Reedy From sullivanz.pku at gmail.com Tue Mar 7 01:22:52 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 6 Mar 2006 22:22:52 -0800 Subject: Confused by Method(function) of a module and method of a class/instance Message-ID: <1141712572.831656.326200@u72g2000cwu.googlegroups.com> In python, these expression seems yields the same result: inputstring='ABC' print inputstring.lower() print lower(inputstring) print string.lower(inputstring) result: abc abc abc Question: Is the method lower() just a method for the inputstring instance( an instrance object of a string class object), or a function in the module string.py or a build-in function or sth else? Why do the three expression yield the same result "abc"? From totalgeekdom at gmail.com Thu Mar 16 22:54:21 2006 From: totalgeekdom at gmail.com (totalgeekdom at gmail.com) Date: 16 Mar 2006 19:54:21 -0800 Subject: Large algorithm issue -- 5x5 grid, need to fit 5 queens plus some squares In-Reply-To: <1142492189.848731.3950@j52g2000cwj.googlegroups.com> References: <1142484909.490742.152390@j33g2000cwa.googlegroups.com> <1142492189.848731.3950@j52g2000cwj.googlegroups.com> Message-ID: <1142567661.742881.222870@v46g2000cwv.googlegroups.com> Sorry to bring this up again, but I decided to try to re-create the program, using the 2d array. However, I ran into a slight problem. How will the permutation function have to be modified? I'm having issues trying to figure out how it works, and how it would need to be modified to use it correctly (I used it from a cookbook, and didn't bother figuring it out) From tim at pollenation.net Sun Mar 26 13:23:32 2006 From: tim at pollenation.net (Tim Parkin) Date: Sun, 26 Mar 2006 19:23:32 +0100 Subject: SSH, remote login, and command output In-Reply-To: References: Message-ID: <4426DC24.1080001@pollenation.net> Spire 01 wrote: > Greetings! > > I'm working on a Python program for a small LAN of Linux systems running > Gentoo, and I need a little help figuring out what I need to do it. So > what I'd like to do is, from any given computer, log on to every other > computer, run a certain command (which normally outputs text to the > terminal), and store the output so I can use the aggregate statistics > later in the program. I would normally something along the lines of SSH > to do it, but I don't know what I would need to pull that off in > Python. There's also one complication: the systems could be Gentoo > systems, or they could be logged into Windows since they're dual > booted. Considering all of this, can anyone give me some recommendation > as to what library I should learn how to use to pull this off? I admit, > I haven't done too much in the way of networks, but if someone can tell > me what I need to do remote logins in this way, I'll do what I can to > make it work. > > Thanks a million! > Spire I wrote a small tool to implement cron like functionality over ssh using twisted (with public/private keys). This was written to scratch a small itch but also to learn how twisted works with conch, it's ssh module. http://crontorted-project.pollenation.net/cgi-bin/trac.cgi Feel free to use, I haven't put a license on it but it would be MIT/BSD .. contact me if you want an explicit confirmation. Tim Parkin From bencvt at gmail.com Mon Mar 20 19:52:31 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 20 Mar 2006 16:52:31 -0800 Subject: what's the general way of separating classes? In-Reply-To: References: <441f02c5$0$29624$636a55ce@news.free.fr> Message-ID: <1142902351.300229.325320@g10g2000cwb.googlegroups.com> John Salerno wrote: > bruno at modulix wrote: > > >> It seems like this can > >> get out of hand, since modules are separate from one another and not > >> compiled together. You'd end up with a lot of import statements. > > > > Sorry, but I don't see the correlation between compilation and import > > here ? > > I meant that in a language like C#, which compiles all the separate > files into one program, it is not necessary to have the equivalent of an > import/include type of statement. Er? Surely you've used C#'s "using" statement? Apples and oranges, but: C#'s "using Foo.Bar;" is roughly analogous to Python's "from foo.bar import *". C#'s "int x = Foo.Bar.f();" is roughly analogous to Python's "import foo.bar; x = foo.bar.f()". > You can just refer to the classes from > any other file. Iff they're in the same namespace. You can have multiple namespaces in the same .NET assembly, you know. > But in Python, without this behavior, you must > explicitly import any external files. That's true. Each Python file is essentially its own namespace. And when, say, __init__.py does a "from submodule import *" it essentially merges submodule's namespace into its own. --Ben From bobrien18 at yahoo.com Mon Mar 6 14:45:42 2006 From: bobrien18 at yahoo.com (KraftDiner) Date: 6 Mar 2006 11:45:42 -0800 Subject: Need help initializing a list or tuple. In-Reply-To: <1141674074.417716.158780@p10g2000cwp.googlegroups.com> References: <1141664498.539402.43160@e56g2000cwe.googlegroups.com> <1141667358.694629.91840@j52g2000cwj.googlegroups.com> <1141674074.417716.158780@p10g2000cwp.googlegroups.com> Message-ID: <1141674342.729592.45440@v46g2000cwv.googlegroups.com> Oh by the way the b = sum(a, []) worked well to convert the two dimensional array to a 1D array... Is there a way to bring that 1D array back to a 2D array? From mtobis at gmail.com Wed Mar 29 18:45:08 2006 From: mtobis at gmail.com (Michael Tobis) Date: 29 Mar 2006 15:45:08 -0800 Subject: Try Python! In-Reply-To: <1143667470.851465.284830@i39g2000cwa.googlegroups.com> References: <1143663801.542233.206500@u72g2000cwu.googlegroups.com> <1143667470.851465.284830@i39g2000cwa.googlegroups.com> Message-ID: <1143675907.958211.253820@j33g2000cwa.googlegroups.com> We had some discussion of this in the edu-sig meeting at PyCon. I alleged that I had read that there is no such thing as a Python sandbox. Others claimed that one could simply preprocess and disallow "dangerous" constructs. My allegation was based on an argument from authority; I recalled reading the assertion from one of the c.l.p. regulars that I consider authoritative, though I don't remember which (Frederick, Alex, Aahz perhaps?). This is all in relation to why the rexec module went away, and is certainly relevant to what can be achieved in the sphere of teaching with python in general, and teaching python with python in particular. I refer you in particular to these messages from BDFL: http://mail.python.org/pipermail/python-dev/2002-December/031246.html http://mail.python.org/pipermail/python-dev/2002-December/031251.html So what is the scoop? Why does Guido say there is no such thing as a secure Python, and (as is generally reasonable) presuming he is correct on the matter, how can these sites work safely? thanks mt From robert.kern at gmail.com Thu Mar 2 22:39:05 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 02 Mar 2006 21:39:05 -0600 Subject: how to overload sqrt in a module? In-Reply-To: References: Message-ID: Michael McNeil Forbes wrote: > Here is one fairly ugly solution: > > module_g.py > ----------- > def g(x,math): > return math.sqrt(x) > > >>>>import math, cmath, module_g >>>>module_g.g(2,math) > > 1.4142135623730951 > >>>>module_g.g(-2,cmath) > > 1.4142135623730951j > > I am sure there is a better way of doing this that makes use of the > type of the argument (Dynamical scoping would solve the > problem but we don't want to go there...). Note that the following > function would work fine > > def f(x): > return abs(x) > > because of the special member __abs__ attached to the type. There is no > corresponding member for sqrt, sin etc. > > What is the "proper" pythonic way to do this? Use the appropriate library which already implements the features you want. In [8]: class A(object): ...: def __init__(self, x): ...: self.x = x ...: def sqrt(self): ...: return 2*self.x ...: ...: In [9]: a = A(10) In [10]: import numpy In [11]: numpy.sqrt(a) Out[11]: 20 In [12]: numpy.sqrt(10) Out[12]: 3.1622776601683795 In [13]: numpy.sqrt(10j) Out[13]: (2.2360679774997898+2.2360679774997898j) -- Robert Kern robert.kern at gmail.com "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tzot at sil-tec.gr Fri Mar 3 04:19:08 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Fri, 03 Mar 2006 11:19:08 +0200 Subject: PEP 354: Enumerations in Python References: <87accdplbj.fsf@rose.polar.local> <1141021828.706947.156270@u72g2000cwu.googlegroups.com> Message-ID: On 26 Feb 2006 22:30:28 -0800, rumours say that "Crutcher" might have written: >This seems great, except why can't I compare strings? It seems too >useful when dealing with user input, or parsing messages or config >files. > >>>> Weekdays = enum('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat') >>>> Weekdays.mon.__cmp__('mon') some_value = Weekdays.thu ... user_input = raw_input("Enter day name") if user_input == str(some_value): >Additionaly, perhaps the call method of the enumeration object should >construct a value from strings? >>>> Weekdays.mon == Weekdays('mon') Either way works for me. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From robin at NOSPAMreportlab.com Mon Mar 27 02:43:12 2006 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Mon, 27 Mar 2006 07:43:12 +0000 Subject: New-style Python icons In-Reply-To: References: <1142873819.773536.11300@v46g2000cwv.googlegroups.com> Message-ID: <44279790.7020708@jessikat.plus.net> Steven Bethard wrote: ....... >> >> http://www.doxdesk.com/img/software/py/icons.zip > > I just wanted to say that I've been using these icons for almost a week > now and I love them! I'd like to reiterate EuGeNe's request that these > go into the Python 2.5 release if at all possible. > > STeVe Whilst admitting that my preference is purely old fogeyism, I prefer the older icons. However, there is one aspect which seems to be forgotten. These logos/icons are much more abstract and so harder to describe verbally. It's pretty easy to describe the existing Python icons: "can you see a green snake on your desktop?". How does one describe these new icons? -- Robin Becker From tuvas21 at gmail.com Sat Mar 4 12:30:49 2006 From: tuvas21 at gmail.com (Tuvas) Date: 4 Mar 2006 09:30:49 -0800 Subject: Random Prime Generator/Modular Arithmetic In-Reply-To: <1hbo45c.6kg75cbrxcaiN%aleaxit@yahoo.com> References: <1141487100.450422.306010@v46g2000cwv.googlegroups.com> <1hbo45c.6kg75cbrxcaiN%aleaxit@yahoo.com> Message-ID: <1141493449.312867.225160@j33g2000cwa.googlegroups.com> Well, the RSA element's never going to encrypt more than a small, 1 block system except under rare occasions, the primary encryption will be AES128. Thanks for the help though! From klaus at seistrup.dk Sat Mar 18 05:41:01 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Sat, 18 Mar 2006 10:41:01 +0000 (UTC) Subject: filter list fast References: <1142675680.468064.167930@v46g2000cwv.googlegroups.com> Message-ID: Lars Woetmann wrote: > I have a list I filter using another list and I would like > this to be as fast as possible > right now I do like this: > > [x for x in list1 if x not in list2] > > i tried using the method filter: > > filter(lambda x: x not in list2, list1) > > but it didn't make much difference, because of lambda I guess > is there any way I can speed this up If you use a reasonably new python version, you could use sets: #v+ >>> a = set(range(10)) >>> a set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> b = set(range(5, 15)) >>> b set([5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) >>> a.difference(b) set([0, 1, 2, 3, 4]) >>> a-b set([0, 1, 2, 3, 4]) >>> list(a-b) [0, 1, 2, 3, 4] >>> #v- Cheers, -- Klaus Alexander Seistrup SubZeroNet, Copenhagen, Denmark http://magnetic-ink.dk/ From robert.kern at gmail.com Fri Mar 3 11:46:16 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 03 Mar 2006 10:46:16 -0600 Subject: scipy In-Reply-To: <1141376654.536347.40120@z34g2000cwc.googlegroups.com> References: <1141376654.536347.40120@z34g2000cwc.googlegroups.com> Message-ID: computer1 wrote: > I want to install scipy 0.4.6 (windows)on my computer ,but i cannot > download it from www.scipy.org. who can tell me another place to > download it? http://www.scipy.org/Download links to the Sourceforge download site. I assume that you are trying to download the files by simply right-clicking the URL and picking "Save Link As..." from the context menu (or whatever it is in your browser). Sourceforge has a mirror selection system that gets in the way. Just click on the link, and select an appropriate mirror from that page. Then your real download will continue. I expect that we will be placing tarballs on PyPI soon. -- Robert Kern robert.kern at gmail.com "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From just at xs4all.nl Fri Mar 10 13:30:16 2006 From: just at xs4all.nl (Just) Date: Fri, 10 Mar 2006 19:30:16 +0100 Subject: First script, please comment and advise References: <1141917596.011498.311500@p10g2000cwp.googlegroups.com> <1141920446.935210.260650@j52g2000cwj.googlegroups.com> <1141936277.648924.119020@z34g2000cwc.googlegroups.com> Message-ID: In article <1141936277.648924.119020 at z34g2000cwc.googlegroups.com>, bearophileHUGS at lycos.com wrote: > >1. The fact that one function calls the other doesn't mean they're > >"logically nested".< > > In this situation they were logically nested, because the scramble_word > is a function needed by another one only, in Java the scramble_word > becomes a (private) method of a text scrambling class; this means it is > nested and hided inside a class. Pascal languages were pre-OOP and they > used nested function for similar purposes, that it to hide and > structure functions inside other ones, that in OO languages like Java, > ObjectPascal, Python, etc. you usually do with classes. In Python one usually doesn't try to hide things. [ ... ] > >4. I don't buy the namespace pollution argument, we have modules after all. > > I presume Guido agrees that function nesting is another way to avoid > namespace pollution :-) I dare you to find out. I'm fairly sure of the answer. > There are many ways to do the same thing, to > avoid pollution in one module. Nesting functions is not one of them. Factoring a bit of functionality into a helper function, giving that function a name and sticking it into a module can _hardly_ be called "pollution". That's what modules are *for*. [ ... ] > >To me, nested functions (in Python) are *only* helpful when using closures. > >If you're not using the enclosing scope, you're just obfuscating things.< > > Note that until recent time, Python nested scopes were managed quite > differently (in a bad way), Yup. > and yet, they regarded the function nesting > useful enough to be kept anyway. Nested functions are supported because you _need_ them if you want to work with closures. Not because it's a good way to structure code in the *absence* of closures. > I don't agree with you, but every programmer is diffent, because their > story is different. If you have learnt to program with Java/C then you > probably don't like nested functions. If you started with a Pascal-like > language then probably you like that nesting more. If you start with a > Scheme/Lisp background you progrably write Python programs like the > good Norvig: > http://aima.cs.berkeley.edu/python/utils.py That's pretty good code. Well documented, clearly written, uses some functional idioms in a sensible way. And no, it doesn't use gratuitous nested functions. > Maybe other people here can say what they think about this topic, it's > just a relaxed discussion. Sure, it's just that I feel strongly that your advice is not a good one (*especially* for beginners). So I repeat: using nested functions are NOT a good way to factor your code. (I don't need to add "in Python" there, do I?) Just From rutt at bmi.osu.edu Mon Mar 6 11:19:06 2006 From: rutt at bmi.osu.edu (Benjamin Rutt) Date: Mon, 06 Mar 2006 11:19:06 -0500 Subject: sys.stdin.readline() results in extra space send to stdout Message-ID: <5vslpvr1fp.fsf@akron.bmi.ohio-state.edu> There has been a problem that has been bugging me for a while for reading input from standard in. Consider the following simple program: #!/usr/bin/env python import sys print 'enter something: ', answer = sys.stdin.readline().strip() print 'you answered {%s}' % (answer) When I run this interactively, the following happens: $ ~/tmp/foo.py enter something: hi you answered {hi} Notice the extra space before 'you'; I did not put it there. It seems that this problem can be avoided if I instead use the program: #!/usr/bin/env python import code answer = code.InteractiveConsole().raw_input('enter something: ') print 'you answered {%s}' % (answer) Now, the output is: $ ~/tmp/foo.py enter something: hi you answered {hi} Is this a well-known problem? Is it a bug? I do not see why that extra space is getting there in the first version. Using the code module seems a little dirty, when sys.stdin is available. This is python 2.4 on a Linux platform. Thank you, -- Benjamin Rutt From ikshefem at gmail.com Wed Mar 22 12:00:49 2006 From: ikshefem at gmail.com (ikshefem at gmail.com) Date: 22 Mar 2006 09:00:49 -0800 Subject: string.upto() and string.from() In-Reply-To: <442173ff$1_3@newspeer2.tds.net> References: <1143038492.748562.267150@i40g2000cwc.googlegroups.com> <442173ff$1_3@newspeer2.tds.net> Message-ID: <1143046848.975294.287350@i40g2000cwc.googlegroups.com> Sure, you're right I forgot about rsplit ! I guess the negative indexes & al could be done with sep.join(xyz.split(sep)[:index]) Thanks ! From peter at engcorp.com Fri Mar 24 08:53:52 2006 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Mar 2006 08:53:52 -0500 Subject: Remove integer from float number In-Reply-To: <1143184126.831239.214460@t31g2000cwb.googlegroups.com> References: <1226859e35171a3@corp.supernews.com> <1143184126.831239.214460@t31g2000cwb.googlegroups.com> Message-ID: kpp9c wrote: > okay... out of curiousity... how would you then seperate the interger > value from the fractional part do something to one side and then put it > back together... like if you had 8.01 and you want to add to the '8' > part in one way (ordinary decimal) and add to the .01 part modulo > something .. like say modulo 12 so that adding .11 to 8.01 would give > you 9.0 ... I believe math.modf() may be what you're looking for. From tjreedy at udel.edu Wed Mar 29 17:09:41 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 29 Mar 2006 17:09:41 -0500 Subject: a hobbyist's dilemma References: <6uAWf.1851$No6.41879@news.tufts.edu> Message-ID: "John Salerno" wrote in message news:6uAWf.1851$No6.41879 at news.tufts.edu... >> Try creating simple games using PyGame. Think of simple things like >> minesweeper. >> > > Actually, PyGame *is* something I am interested in experimenting with. I > definitely want to use it, but I also want to try some stuff with the > basics too, just so I don't immediately get into the complicated stuff > without working with the usual things first, like lists and > dictionaries, etc. So start with a game that is playable with a text interface. Perhaps hangman, perhaps with a different metaphor ;-) That requires basic i/o, lists, import of random module, and conditional statements. tjr From jess.austin at gmail.com Wed Mar 8 23:16:56 2006 From: jess.austin at gmail.com (jess.austin at gmail.com) Date: 8 Mar 2006 20:16:56 -0800 Subject: generators shared among threads References: <1141497912.606351.232440@j33g2000cwa.googlegroups.com> <1hbo9a3.1pfr3uy160d79iN%aleaxit@yahoo.com> <7xzmk2nhu9.fsf@ruckus.brouhaha.com> <1141779301.471629.157640@e56g2000cwe.googlegroups.com> <7xmzg18ytg.fsf@ruckus.brouhaha.com> <1hbuhqz.1rv746hou88fqN%aleaxit@yahoo.com> Message-ID: <1141877816.497019.264330@z34g2000cwc.googlegroups.com> I just noticed, if you don't define maxsize in _init(), you need to override _full() as well: def _full(self): return False cheers, Jess From johnjsal at NOSPAMgmail.com Sat Mar 25 15:09:53 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 25 Mar 2006 15:09:53 -0500 Subject: a somewhat off-topic question about linux Message-ID: <_oedne4wPJ9DPrjZnZ2dnUVZ_tWdnZ2d@rcn.net> I'm interested in trying out Linux, probably Ubuntu, but I was wondering which distribution you guys like to use (because it's a pain trying to decide!) and you guys are smart. And to keep it Python related, I'll also ask, is there anything special I need to know about using Python on Linux? Do any things change, or can it be used just as I use it on Windows? Thanks! From asma61 at dsl.pipex.com Fri Mar 17 19:17:40 2006 From: asma61 at dsl.pipex.com (DaveM) Date: Sat, 18 Mar 2006 00:17:40 +0000 Subject: Python compiler References: <44195b7a$0$29204$8fcfb975@news.wanadoo.fr> Message-ID: <9akm12tr5o5dc319343560dl96sm2jo2fv@4ax.com> On Thu, 16 Mar 2006 13:34:14 +0100, "M?ta-MCI" wrote: >Apr?s, vous pourrez aussi fr?quenter le newsgroup : > fr.comp.lang.python >qui a l'avantage d'?tre en fran?ais. But perhaps he's a Flemish speaker - are you trying to start a riot? DaveM From philippe.dalet at voila.fr Wed Mar 29 03:19:38 2006 From: philippe.dalet at voila.fr (pdalet) Date: 29 Mar 2006 00:19:38 -0800 Subject: pySerial: write in a blocking mode In-Reply-To: <122jiieidb70q2b@corp.supernews.com> References: <1143578747.023574.150300@i39g2000cwa.googlegroups.com> <122jiieidb70q2b@corp.supernews.com> Message-ID: <1143620378.652598.301110@j33g2000cwa.googlegroups.com> Hi I have developped a python script to control a rs232c rs485 converter, named pyRS485 with pythoncard on windows. ftp-champo.ac-toulouse.fr/pub/btseo/pdalet/python/ python 2.4 Electronics Applications 20050902.exe The best solution is to send the last character with interrupt. when the TDR is empty an interrupt is generated. An interrupt program is executed to change the state of dtr. Not evident on Windows and linux. I have used temporisation, with different values for a slow pc and speed pc. Philippe Marie dit Dalet FIGEAC FRANCE Grant Edwards a ?crit : > On 2006-03-28, Alejandro wrote: > > Hi: > > > > I'm using pySerial to talk to a RS232 to RS485 converter. In order to > > control the converter, I need to control the DTR line to enable/disable > > de RS485 driver. In particular, I need to : > > > > write a character to the serial port > > set the DTR line to level 1 _after_ the last bit of the character is > > send > > > > So I tried this (ser is the serial port object): > > > > ser.write(x) > > ser.setDTR(1) > > ser.write(x) > ser.drainOutput() > ser.setDTR(1) > > > The problem with this is that the ser.write function returns before the > > character is send, and thus, the DTR line is set too soon. (I checked > > this behaivour with an osciloscope). > > > > I thought that seting the writeTimeout parameter could help, but then I > > realized that the write function wait "up to this time", so it doesn't > > work. > > > > Then I tried waiting some time with time.sleep() after ser.write, but > > the shortest time for time.sleep is to big, and non deterministic, so I > > think this is not an option. > > Linux is not a real-time operating system. The > ser.drainOutput() call is going to have the same granularity > and non-determinism as time.sleep(). > > It sounds like you need a serial board that supports > half-duplex operation. > > -- > Grant Edwards grante Yow! Hand me a pair of > at leather pants and a CASIO > visi.com keyboard -- I'm living > for today! From adam.deprince at gmail.com Fri Mar 24 21:15:17 2006 From: adam.deprince at gmail.com (Adam DePrince) Date: Fri, 24 Mar 2006 21:15:17 -0500 Subject: Incremental Compression In-Reply-To: References: Message-ID: <1143252917.4203.18.camel@localhost.localdomain> On Sat, 2006-03-25 at 03:08 +0200, Eyal Lotem wrote: > Hey. > > I have a problem in some network code. I want to send my packets compressed, > but I don't want to compress each packet separately (via .encode('zlib') or > such) but rather I'd like to compress it with regard to the history of the > compression stream. If I use zlib.compressobj and flush it to get the > packet data, I cannot continue to compress with that stream. Yes, you can. Help on built-in function flush: flush(...) flush( [mode] ) -- Return a string containing any remaining compressed data. mode can be one of the constants Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH; the default value used when mode is not specified is Z_FINISH. If mode == Z_FINISH, the compressor object can no longer be used after calling the flush() method. Otherwise, more data can still be compressed. you want to call mycompressor.flush( zlib.Z_SYNC_FLUSH ) The difference between the flushes is this: 1. Z_SYNC_FLUSH. This basically send enough data so that the receiver will get everything you put in. This does decerase your compression ratio (however, in weird case when I last played with it, it helped.) 2. Z_FULL_FLUSH. This sends enough data so that the receiver will get everything you put in. This also wipes the compressors statistics, so the when you pick up where you left of, the compressor will compress about as well as if you had just started, you are wiping its memory of what it saw in the past. 3. Z_FINISH. This is the default action, this is what is killing you. Good luck - Adam DePrince > > I cannot wait until the end of the stream and then flush, because I need to > flush after every packet. > > Another capability I require is to be able to copy the compression stream. > i.e: To be able to create multiple continuations of the same compression > stream. Something like: > > a = compressobj() > pre_x = a.copy() > x = a.compress('my_packet1') > # send x > # x was not acked yet, so we must send another packet via the pre_x > compressor > y = pre_x.compress('my_packet2') > > Is there a compression object that can do all this? Ahh, you are trying to "pretune" the compressor before sending a little bit ... I think C-zlib does this, but I don't know for sure. - Adam DePrince From osv at javad.com Fri Mar 3 12:27:26 2006 From: osv at javad.com (Sergei Organov) Date: Fri, 03 Mar 2006 20:27:26 +0300 Subject: Incorrect Decimal-Float behaviour in comparison tests References: Message-ID: "Fredrik Lundh" writes: > "Cassiano, Marco" wrote: > >> I have difficulties with a weird Python 2.4.2 behaviour in comparing >> Decimal to Floats. >> >> For Example : >> >> >> >>> from decimal import Decimal >> >>> a=Decimal('3.7') >> >>> b=6.3 >> >> >>> if a > b :print a,b,'a is greater than b - NOT TRUE!!!!' >> ... else: print a,b,'b is greater than a - CORRECT' >> ... >> >> >> 3.7 6.3 a is greater than b - NOT TRUE!!!! > > is this > > >>> 1.0 > "0" > False > > also a bug ? Well, without reading the manuals I'd expect this to raise an exception instead of yielding of meaningless and confusing result, consider: >>> 1.0 + "0" Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for +: 'float' and 'str' >>> 1.0 > "0" False ??? Though equal/unequal is entirely different story than less/greater, IMHO. I mean >>> 1.0 == "1.0" False >>> 1.0 != "1.0" True is perfectly fine. -- Sergei. From 007 at corenetworks.com.au Thu Mar 30 19:34:13 2006 From: 007 at corenetworks.com.au (Matt) Date: Fri, 31 Mar 2006 11:34:13 +1100 Subject: embed notepad into a frame widget In-Reply-To: <48srstFl629bU1@uni-berlin.de> References: <122hotpiojvre6b@corp.supernews.com> <48srstFl629bU1@uni-berlin.de> Message-ID: <122ou88ivihqhdc@corp.supernews.com> Diez B. Roggisch wrote: > You are pretty wrong being sure :) Under windows, it is indeed possible to > embed certain applications into others - the related technical term is > conveniently called OLE (Object lining and embedding). Thanks, at least I didnt spend two much time on it :) -Matt From neurogasm at gmail.com Fri Mar 24 23:58:46 2006 From: neurogasm at gmail.com (Kun) Date: Fri, 24 Mar 2006 23:58:46 -0500 Subject: send email to string of emails Message-ID: the code below outputs a string of emails (e.g. ['jon at jon.com', 'joe at joe.com'] i would like to somehow send an email to everyone on the string of emails telling them 'thanks for emailing me' anyone know how to do this? much thanks ahead of time. from imaplib import * import getpass, re m = IMAP4("xxxxxxxxxxxxxx") m.login('xxxxx', 'xxxxxx') m.select('Inbox') status, data = m.search(None,'(SUBJECT "BIKES")') assert status=='OK', "Error. Message: %s"%data data = data[0] #you get your results in a list and search returns only one result assert data,"No results" #cool, we have results, but IMAP's search command only returns IDs so we have to fetch #msgs now status,senders = m.fetch(data.replace(' ',','),'(BODY.PEEK[HEADER.FIELDS (FROM)])') assert status=='OK', "Error. Message: %s"%data ''.join([''.join(t) for t in senders]) senderlist =''.join([''.join(t) for t in senders]) emails = re.findall('(\w+@\w+\.\w+)', senderlist) print emails From leipold at ace-net.com Fri Mar 3 16:03:21 2006 From: leipold at ace-net.com (Walter S. Leipold) Date: Fri, 3 Mar 2006 16:03:21 -0500 Subject: Writing an OPC client with Python ? Message-ID: Larry Bates wrote: > pierlau wrote: > > I use an OPC server for connection to DC Drive. > > I would like to write a small OPC client. > > I have the dll OPCDAAuto.dll which contains all class > > and method but I wonder if its possible to instance in > > python the class that are in the dll ? > > You can call methods/functions in a .dll using ctypes. > > http://starship.python.net/crew/theller/ctypes/ If all you want to do is *read* data from the OPC server, there's OPC XML-DA, an XML-based access method for OPC data. It should be possible to access OPC data using a SOAP library. Warning: Some OPC servers don't support the XML-DA protocol.) I haven't seen XML-DA done in Python yet (I've been meaning to write a Python proof-of-concept for a year or more), but implementations in other languages can be found via Google. In case anybody's wondering, OPC is "OLE for Process Control", the alleged 'open' standard for interfacing instruments and controls to HMI, SCADA, and MES systems in industrial environments. Microsoft's sponsorship of the OPC Foundation was a brilliant piece of anti-competitive marketing; all of the control system vendors have now standardized on OPC, and it's essentially impossible to deploy any process monitoring or control computer that doesn't speak OLE (i.e., that doesn't run Windows). (And, yes, I think it's idiotic for companies to build billions of dollars worth of new manufacturing facilities whose information infrastructures depend on a deprecated, single-vendor 'standard' like OLE. And who the heck wants a 'protocol' that isn't specified at the wire level, anyway?) -- Walt "As long as you've lit one candle, you're allowed to curse the darkness." From fredrik at pythonware.com Sat Mar 18 04:55:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 18 Mar 2006 10:55:07 +0100 Subject: Random Number Generator Error References: <20060318093602.79484.qmail@web36409.mail.mud.yahoo.com> Message-ID: "ahmet nurlu" wrote: > It gives error: > Traceback (most recent call last): > File "random.py", line 2, in ? > from pylab import * > File "/usr/lib/python2.4/site-packages/pylab.py", line 1, in ? > from matplotlib.pylab import * > File "/usr/lib/python2.4/site-packages/matplotlib/pylab.py", line 196, in ? > import mlab #so I can override hist, psd, etc... > File "/usr/lib/python2.4/site-packages/matplotlib/mlab.py", line 58, in ? > import sys, random > File "/home/ofenerci/workspace/random.py", line 11, in ? > if (rand() > 0.5): > NameError: name 'rand' is not defined > [3] Done gedit random.py if you look at the filenames in that traceback, you'll notice that when matplotlib imports the random module, it loads your test program instead of the expected standard library module. to fix this, rename your test program. From johnjsal at NOSPAMgmail.com Mon Mar 20 15:59:02 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 20 Mar 2006 20:59:02 GMT Subject: why isn't Unicode the default encoding? In-Reply-To: References: Message-ID: Robert Kern wrote: >> I figured this might have something to do with it, but then again I >> thought that Unicode was created as a subset of ASCII and Latin-1 so >> that they would be compatible...but I guess it's never that easy. :) > > No, it isn't. You seem to be somewhat confused about Unicode. At least you are > misusing terminology quite a bit. You may want to read the following articles: I meant to say 'superset' From fredrik at pythonware.com Thu Mar 9 17:26:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 9 Mar 2006 23:26:32 +0100 Subject: Silly import question (__file__ attribute) References: <1141941885.824586.151680@v46g2000cwv.googlegroups.com> Message-ID: "mh" wrote: > So on most modules I import, I can access the .__file__ attribute to > find the implementation. ie: > >>> import time > >>> time.__file__ > '/data1/virtualpython/lib/python2.3/lib-dynload/timemodule.so' > >>> import socket > >>> socket.__file__ > '/data1/virtualpython/lib/python2.3/socket.pyc' > > This doesn't work on the "thread" module: > >>> import thread > >>> thread.__file__ > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute '__file__' > > A few questions. Why? Where is thread.py or thread.so? (I can't find > it). >>> import sys >>> "thread" in sys.builtin_module_names True From mforbes at lnsDOTmit.edu Fri Mar 3 00:44:09 2006 From: mforbes at lnsDOTmit.edu (Michael McNeil Forbes) Date: Thu, 2 Mar 2006 21:44:09 -0800 Subject: how to overload sqrt in a module? In-Reply-To: References: Message-ID: > Michael McNeil Forbes wrote: >> Here is one fairly ugly solution: >> >> module_g.py >> ----------- >> def g(x,math): >> return math.sqrt(x) >> >> >>>>> import math, cmath, module_g >>>>> module_g.g(2,math) >> >> 1.4142135623730951 >> >>>>> module_g.g(-2,cmath) >> >> 1.4142135623730951j >> >> What is the "proper" pythonic way to do this? > On Thu, 2 Mar 2006, Robert Kern wrote: > > Use the appropriate library which already implements the features you want. > > In [8]: class A(object): > ...: def __init__(self, x): > ...: self.x = x > ...: def sqrt(self): > ...: return 2*self.x > ...: > ...: > > In [9]: a = A(10) > > In [10]: import numpy > > In [11]: numpy.sqrt(a) > Out[11]: 20 > > In [12]: numpy.sqrt(10) > Out[12]: 3.1622776601683795 > > In [13]: numpy.sqrt(10j) > Out[13]: (2.2360679774997898+2.2360679774997898j) > > -- > Robert Kern Thanks. This solution is essentially to make sure that all "numeric" objects have .sqrt etc. members, and then use a library which check against builtin types and custom types with these extensions. That works, as long as the appropriate library exists (or I write it myself) (and this works in my case: I did not realize that the numpy/scipy functions worked this way.) Are there any other more generic solutions (without having to write "custom" functions like numpy.sqrt)? Michael From PPNTWIMBXFFC at spammotel.com Wed Mar 22 03:50:11 2006 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Wed, 22 Mar 2006 09:50:11 +0100 Subject: From Python to c++ References: <1143011484.441219.58270@t31g2000cwb.googlegroups.com> Message-ID: On Wed, 22 Mar 2006 08:11:24 +0100, nnorwitz at gmail.com wrote: > This is so scary, I probably shouldn't post this. It sounds from your > description, you really want RTTI. I haven't done this in a long > while, so I'm not sure there is an easier way. But the program below > works and seems like it may be what you are asking for. Perfect! That is precisely what I was looking for. I can easily adapt it for my needs! Thanks a lot. Regards, Marco From tjreedy at udel.edu Thu Mar 9 18:33:55 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 9 Mar 2006 18:33:55 -0500 Subject: advice on this little script References: <2bSdncWWK7aINpLZRVn-vA@rcn.net><2bSdncqWK7aJN5LZRVn-vA@rcn.net><1141877919.475753.27060@j33g2000cwa.googlegroups.com><1141879051.021695.290570@j52g2000cwj.googlegroups.com> Message-ID: "John Salerno" wrote in message news:zNKdnYC8ALKCKJLZRVn-qg at rcn.net... > Ben Cartwright wrote: >> BartlebyScrivener wrote: >>> What about a console beep? How do you add that? >>> >>> rpd >> >> Just use ASCII code 007 (BEL/BEEP): >> >> >>> import sys >> >>> sys.stdout.write('\007') >> >> Or if you're on Windows, use the winsound standard module. > > I'd prefer to be platform neutral when possible. Is the first option > that, or does this change depending on OS? It is display dependent what display does with control codes. \007 is ANSI ascii control char which only works to beep on ansi terminals or emulation thereof. On PCs and Windows, displays have extended char set that prints most all char codes. \007 prints as a square box. IBM EBCDIC terminals would probably do third thing. Terry Jan Reedy From zbir at urbanape.com Wed Mar 15 12:53:27 2006 From: zbir at urbanape.com (Zachery Bir) Date: Wed, 15 Mar 2006 12:53:27 -0500 Subject: how to get 20000 html pages content quickly from one server? In-Reply-To: <1142441926.525376.312030@i40g2000cwc.googlegroups.com> References: <1142439755.840346.181060@p10g2000cwp.googlegroups.com> <1142441572.689735.273320@j33g2000cwa.googlegroups.com> <1142441926.525376.312030@i40g2000cwc.googlegroups.com> Message-ID: <39700E30-B807-44BF-A32A-B4C514F7CADF@urbanape.com> On Mar 15, 2006, at 11:58 AM, JuHui wrote: > in fact, I want to do a script to get news on others site. > I must use script get the content and analyze the html code, where is > the title, where is the body.... > so, I can't ask permission, use wget and "Physically remove the > harddrive and reinstall it locally" The only one it looks like you *can't* do is physically remove the hard drive and reinstall it locally. Seems more like you *won't* do the other two. Zac From piton123 at yahoo.com Sat Mar 18 20:21:01 2006 From: piton123 at yahoo.com (Bob Piton) Date: 19 Mar 2006 01:21:01 -0000 Subject: POP3 Mail Download References: <7g1p12ttfcf1sd5v9rrggr6ioushs2e1id@4ax.com> Message-ID: On Sat, 18 Mar 2006 18:34:56 -0500, Kevin F wrote: > Dennis Lee Bieber wrote: >> On Sat, 18 Mar 2006 17:24:05 -0500, Kevin F >> declaimed the following in comp.lang.python: >> >>> I fixed the indentation to: >>> >>> emails = [] >>> for msg in messagesInfo: >>> msgNum = int(split(msg, " ")[0] >>> msgSize = int(split(msg, " ")[1] >> >> Now look at your parentheses... >>> and it still doesn't work, what's wrong? >> >>> msgNum = int(split(msg, " ")[0] >> HINT: 0 1 2 1 ? > i have no idea what you are hinting at, can you please just tell me what i > need to change? I know how you feel; it's brutal trying to get elementary information from this group. I think what he is hinting at is that you are missing a right parentheses. msgNum = int(split(msg, " ")[0] should be: msgNum = int(split(msg, " "))[0] msgSize = int(split(msg, " ")[1] should be: msgSize = int(split(msg, " "))[1] Now if only somebody would tell me, with elementary examples, how you write to the thing called 'stdout' and how you read from 'stdin'. From duncan.booth at invalid.invalid Sun Mar 5 04:37:03 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Mar 2006 09:37:03 GMT Subject: raw strings and \ References: <1141548565.145199.145910@e56g2000cwe.googlegroups.com> Message-ID: wrote: > I thought I understood raw strings, then I got bitten by this: > > x=r'c:\blah\' > > which is illegal! I thought that \ had no special meanning in a raw > string so why can't it be the last character? No, the backslash is still special in terms of parsing the string, it is simply that once the string has been parsed escape sequences are not interpreted. > > making me do: > > x=r'c:\blah' '\\' > > is just silly... > > Yes, that is silly. You could alternatively do: x = 'c:/blah/' or x = 'c:\\blah\\' But why would you want to end your path with a literal backslash anyway? Get into the habit of using the os.path module for all manipulations of file paths and you never need to worry about this sort of thing again. This sort of thing should work well enough: folder = 'c:/blah' for line in open(os.path.join(folder, 'data.txt')): print line From bluszcz at jabberpl.org Wed Mar 15 12:53:28 2006 From: bluszcz at jabberpl.org (Rafal Zawadzki) Date: Wed, 15 Mar 2006 18:53:28 +0100 Subject: problem with python zsi Message-ID: Hi. I tried earlier to write python zsi mail list, but nobody answered. I am using ZSI 1.7/2.0rc1 with TTPro Soap SDK. The wsdl file can be found here: http://demo.seapine.com/ttsoapcgi.wsdl My wsdl is the same, only different is the address of the cgi file. for example i cannot use defectRequest method: req = getDefectRequest() req._defectNumber = 140 req._cookie = cookie #cookie is valid int resp = server.getDefect(req) What i get: _________________________________ Wed Mar 15 10:42:17 2006 REQUEST: 197437140 _________________________________ Wed Mar 15 10:42:17 2006 RESPONSE: 500 Internal Server Error ------- Date: Wed, 15 Mar 2006 09:41:37 GMT Server: Apache/1.3.33 (Debian GNU/Linux) Content-Length: 586 Content-Type: text/xml; charset=utf-8 Connection: close SOAP-ENV:ClientXML syntax error Traceback (most recent call last): File "./tt.py", line 42, in ? resp = server.getDefect(req) File "/home/bluszcz/python/testtrack/ttsoapcgi_services.py", line 285, in getDefect response = self.binding.Receive(getDefectResponse.typecode) File "/usr/lib/python2.4/site-packages/ZSI/client.py", line 415, in Receive raise FaultException(msg) ZSI.FaultException: XML syntax error The second error: req = getGlobalUserListRequest() req._cookie=cookie resp = server.getGlobalUserList(req) _________________________________ Wed Mar 15 10:47:15 2006 REQUEST: 197437 _________________________________ Wed Mar 15 10:47:15 2006 RESPONSE: 200 OK ------- Date: Wed, 15 Mar 2006 09:46:34 GMT Server: Apache/1.3.33 (Debian GNU/Linux) Content-Length: 537 Content-Type: text/xml; charset=utf-8 Traceback (most recent call last): File "./tt.py", line 40, in ? resp = server.getGlobalUserList(req) File "/home/bluszcz/python/testtrack/ttsoapcgi_services.py", line 454, in getGlobalUserList response = self.binding.Receive(getGlobalUserListResponse.typecode) File "/usr/lib/python2.4/site-packages/ZSI/client.py", line 421, in Receive reply = self.ps.Parse(tc) File "/usr/lib/python2.4/site-packages/ZSI/parse.py", line 319, in Parse return how.parse(self.body_root, self) File "/usr/lib/python2.4/site-packages/ZSI/TCcompound.py", line 199, in parse '" missing from struct', ps.Backtrace(elt)) ZSI.EvaluateException: Element "_GlobalUserList" missing from struct [Element trace: /SOAP-ENV:Envelope/SOAP-ENV:Body/ttns:getGlobalUserListResponse] But when I am using ZSI 1.7: req = getDefectRequestWrapper() req._defectNumber = 140 req._cookie = int(cookie) resp = server.getDefect(req) I got correct XML but python fault: Traceback (most recent call last): File "./tt.py", line 47, in ? resp = server.getDefect(req) File "/home/bluszcz/python/testtrack/ttsoapcgi_services.py", line 850, in getDefect response = self.binding.Receive(getDefectResponseWrapper()) File "/usr/lib/python2.4/site-packages/ZSI/client.py", line 325, in Receive return self.ps.Parse(tc) File "/usr/lib/python2.4/site-packages/ZSI/parse.py", line 311, in Parse return how.parse(self.body_root, self) File "/usr/lib/python2.4/site-packages/ZSI/TCcompound.py", line 107, in parse value = what.parse(c_elt, ps) File "/usr/lib/python2.4/site-packages/ZSI/TCcompound.py", line 107, in parse value = what.parse(c_elt, ps) File "/usr/lib/python2.4/site-packages/ZSI/TCcompound.py", line 327, in parse item = self.ofwhat.parse(c, ps) File "/usr/lib/python2.4/site-packages/ZSI/TCcompound.py", line 72, in parse self.checkname(elt, ps) File "/usr/lib/python2.4/site-packages/ZSI/TC.py", line 141, in checkname if self.nspname and ns != self.nspname: AttributeError: CReportedByRecord_Def instance has no attribute 'nspname' another: one thing: 1.7 request: 197600 140 2.0 request: 197644140 according to: http://sourceforge.net/mailarchive/message.php?msg_id=10277851 I added: * if name or 1: * but now I have got: Traceback (most recent call last): File "./tt.py", line 47, in ? resp = server.getDefect(req) File "/home/bluszcz/python/testtrack/ttsoapcgi_services.py", line 850, in getDefect response = self.binding.Receive(getDefectResponseWrapper()) File "/usr/lib/python2.4/site-packages/ZSI/client.py", line 325, in Receive return self.ps.Parse(tc) File "/usr/lib/python2.4/site-packages/ZSI/parse.py", line 311, in Parse return how.parse(self.body_root, self) File "/usr/lib/python2.4/site-packages/ZSI/TCcompound.py", line 111, in parse raise e ZSI.EvaluateException: getDefectResponse._pDefect: pDefect.eventlist: Sorry, no multi-dimensional arrays [Element trace: /SOAP-ENV:Envelope/SOAP-ENV:Body/ttns:getDefectResponse/pDefect/eventlist/item[2]] -- ?? ,,To jest Unix. Daje Ci wystarczaj?co du?o liny, aby? m?g? si? powiesi?.'' Miquel van Smoorenburg miquels at cistron.nl From eddie at holyrood.ed.ac.uk Thu Mar 2 06:40:25 2006 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Thu, 2 Mar 2006 11:40:25 +0000 (UTC) Subject: telnetlib problems References: <1141153872.182746.289830@t39g2000cwt.googlegroups.com> <1141232566.484414.282690@i40g2000cwc.googlegroups.com> Message-ID: vercingetorix52 at yahoo.com writes: >Thanks for the reply. I've replaced the call to read_very_eager() with >read_until() and enabled debugging messages. My script now looks like >this... >############################# >import telnetlib >tn = telnetlib.Telnet('192.168.100.11') >tn.set_debuglevel(9) >tn.read_until('login: ', 5) >tn.write('user\n') >tn.read_until('Password: ', 5) >tn.write('password\n') >tn.read_until('bash-2.05$ ', 5) >tn.write('ls\n') >print tn.read_until('bash-2.05$ ', 5) >############################# >Each call to read_until() returns a valid string except for the second >one, i.e., >tn.read_until('Password: ', 5) returns a null string. >Here's the program output with debugging enabled... >############################# >Telnet(192.168.100.11,23): recv "\xff\xfd\x18\xff\xfd >\xff\xfd#\xff\xfd'" >Telnet(192.168.100.11,23): IAC DO 24 >Telnet(192.168.100.11,23): IAC DO 32 >Telnet(192.168.100.11,23): IAC DO 35 >Telnet(192.168.100.11,23): IAC DO 39 >Telnet(192.168.100.11,23): recv >'\xff\xfb\x03\xff\xfd\x01\xff\xfd\x1f\xff\xfb\x05\xff\xfd!' >Telnet(192.168.100.11,23): IAC WILL 3 >Telnet(192.168.100.11,23): IAC DO 1 >Telnet(192.168.100.11,23): IAC DO 31 >Telnet(192.168.100.11,23): IAC WILL 5 >Telnet(192.168.100.11,23): IAC DO 33 >Telnet(192.168.100.11,23): recv '\xff\xfb\x03' >Telnet(192.168.100.11,23): IAC WILL 3 >Telnet(192.168.100.11,23): recv '\xff\xfb\x01Embedded Systems, 2050 >Single Board Computer.\r\nR' >Telnet(192.168.100.11,23): IAC WILL 1 >Telnet(192.168.100.11,23): recv 'uning \\s Kernel \\r.\r\nEmbedded: >2050 Special Feature' >Telnet(192.168.100.11,23): recv 's Enabled.\r\n\r\n' >Telnet(192.168.100.11,23): recv 'login: ' >Telnet(192.168.100.11,23): send 'user\n' >Telnet(192.168.100.11,23): send 'password\n' >Telnet(192.168.100.11,23): recv 'Password: ' >Telnet(192.168.100.11,23): send 'ls\n' >Telnet(192.168.100.11,23): recv '\r\n' >Telnet(192.168.100.11,23): recv 'Login incorrect\r\n\r\nlogin: ' >Login incorrect >login: >############################# >It looks like it's sending the password before receiving the password >prompt. It looks more like it's taking longer than 5 seconds to receive the Password: prompt so it times out, returns to your code and you send the next string anyway but (assuming this is a valid password) the far end might throw away any pending input when it finally does send the Password: prompt (otherwise it would probably have got back in sync). In short you shouldn't go past each stage unless you've verified that you got the expected response. I can't actually remember exactly what the responses signify but at a minimum I assume the empty string means there's no point in continuing because what you expected to see wasn't there so you need to either abort or try some recovery process. And also make sure you give it a reasonable time to respond. Eddie From johnjsal at NOSPAMgmail.com Sat Mar 4 01:19:17 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 04 Mar 2006 01:19:17 -0500 Subject: slicing the end of a string in a list In-Reply-To: References: <1141374847.159701.29680@i40g2000cwc.googlegroups.com> <1141376618.133583.103580@i39g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Fri, 03 Mar 2006 16:57:10 +0000, John Salerno wrote: > >> Steven D'Aprano wrote: >> >>> The important term there is BINARY, not large. Many problems *reading* >>> (not opening) binary files will go away if you use 'rb', regardless of >>> whether they are small, medium or large. >> Is 'b' the proper parameter to use when you want to read/write a binary >> file? I was wondering about this, because the book I'm reading doesn't >> talk about dealing with binary files. > > The interactive interpreter is your friend. Call help(file), and you will > get: > > class file(object) > | file(name[, mode[, buffering]]) -> file object > | > | Open a file. The mode can be 'r', 'w' or 'a' for reading (default), > | writing or appending. The file will be created if it doesn't exist > | when opened for writing or appending; it will be truncated when > | opened for writing. Add a 'b' to the mode for binary files. > > plus extra information. > > Take note that the mode is NOT "b". It is "rb". > > Awesome! I'm trying to push away thoughts of C#'s binary reader and writer classes now. :) From michaeltaft at gmail.com Sun Mar 12 17:47:10 2006 From: michaeltaft at gmail.com (mwt) Date: 12 Mar 2006 14:47:10 -0800 Subject: Help Create Good Data Model In-Reply-To: <1142201751.544046.75150@v46g2000cwv.googlegroups.com> References: <1142107183.358685.266440@i39g2000cwa.googlegroups.com> <1142115988.067193.239570@i39g2000cwa.googlegroups.com> <1142123948.052804.5450@i40g2000cwc.googlegroups.com> <1142197521.068087.72040@v46g2000cwv.googlegroups.com> <1142201751.544046.75150@v46g2000cwv.googlegroups.com> Message-ID: <1142203630.415688.198860@i39g2000cwa.googlegroups.com> The Queue won't work for this app, because it removes the data from the Queue when you query (the way I understand it). From jeff at schwabcenter.com Fri Mar 17 09:23:06 2006 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Fri, 17 Mar 2006 14:23:06 GMT Subject: Counting nested loop iterations In-Reply-To: References: <1142539976.631204.108260@u72g2000cwu.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Joel Hedlund wrote: > >> I've been thinking about these nested generator expressions and list >> comprehensions. How come we write: >> >> a for b in c for a in b >> >> instead of >> >> a for a in b for b in c >> >> More detailed example follows below. >> >> I feel the latter variant is more intuitive. Could anyone please explain the >> fault of my logic or explain how I should be thinking about this? > > out = [a for b in c for a in b] > > can be written > > out = [a > for b in c > for a in b] > > which is equivalent to > > out = [] > for b in c: > for a in b: > out.append(a) > > in other words, a list comprehension works exactly like an ordinary for > loop, except that the important thing (the expression) is moved to the > beginning of the statement. Which is utterly counter-intuitive, the opposite of Perl, and remains one of the most confusing and surprising things I have encountered in Python so far. And nobody start yelling that Python is not Perl. We all know Python is not Perl, nor should it be. If you want different for the sake of different, though, go try MOO or something. Here: http://en.wikipedia.org/wiki/Esoteric_programming_language From grante at visi.com Mon Mar 6 16:30:22 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 06 Mar 2006 21:30:22 -0000 Subject: Pyserial again References: <1141661808.753184.157150@e56g2000cwe.googlegroups.com> <1141665448.418740.167910@i40g2000cwc.googlegroups.com> <120ossf55scsj8b@corp.supernews.com> <1141675566.162480.148260@v46g2000cwv.googlegroups.com> Message-ID: <120pafehu3erb06@corp.supernews.com> On 2006-03-06, Luca wrote: >>> Another point is the textctrl: it store only the first byte >>> and not the other why?, the byte are like 22 and all are >>> readed >> >> No clue. I don't know what "textctrl" is or what it's >> supposed to do. > > a = ser.readline() > a = self.textCtrl3.SetValue(a + ' ') > > For my bad understanding is clear Please, please, quote articles so that we can tell who said what. I've attempted to re-quote things to make it clear. If textctrl isn't doing what you think it should, you need to 1) Create a _small_ program that demonstrates the problem. 2) POST THAT PROGRAM in a thread with a the subject line that is likely to attract the attention of somebody who knows something about "textctrl". >>> Sniffing the data with serial port monitor i see that the >>> answer is ok but after the answer the port close, why? >> >> What makes you think the port closed? >> > > The serial port monitor write com port close. OK. Good. That's useful information. I'm assuming that by "serial port monitor" you mean something like the tool from sysinternals? It's important that you include details like that. In the previous post, I thought you meant you were watching the serial data stream on the cable with a protocol analyzer or with another PC. I didn't understand how you would know the port had been closed by watching the data on the cable. You said you were sniffing the _data_, and you can't tell by looking at _data_ that the port has been closed -- so I had to ask how you knew the port had been closed. Now, if you'll just post the Python code we can probably tell you what's wrong. Since you haven't shown us the code, all we can do is guess. I've already made my guess: the serial port object is going out-of-scope and getting garbage collected. If you don't know what that means, let us know, and we'll explain it in more detail. > As you know i'm not a programmer, but i try to do this in my > free time. That's fine. We're all willing to help, but you have to work with us. The best/fastest way to solve your problem is to write a small program that demonstrates the problem and post it. Then we can look at it and tell you what's wrong. You could post your entire program, but the more code you post, less likely it is that people are going to sort through it to figure out what's wrong. If you can post a 15-20 line program that doesn't do what you think it should, I guarantee you'll get a quick answer explaining what you've done wrong. If you post a 1500 line program, nobody is going to read it. It's theoretically possible to post a precise enough natural language (e.g. English) description of the problem such that somebody might be able to figure out what's wrong. But, writing a description that is precise enough is very difficult even for somebody who is good at Python and a native English speaker. Its much easier to write a small program that demonstrates the problem. > Probably you have reason to write: > > The code you post is irrelevant. > > But i try to do my best as in my possibility. If you want us to tell you what's wrong with your code, you _have_to_show_it_to_us_. It's usually pointless for us to try to guess. There is a big problem with just posting a few lines of code out of a larger program: unless you know what's wrong, you don't know which lines of code to post. If you don't know what the problem is, you're probably posting the wrong chunk of code. > I think that in any case you can't run my code if you haven't > the same device that i have. Even if we can't run the code, we can still look at it. Ideally, you should create a small program that demonstrates your problem. Make it as small as you can. Leave out anything that isn't related to the problem you're trying to solve. If you refuse to post code that demonstrates your problem, there's very little chance we'll correctly guess what you've written. > So i don't want that you loose time with my stupid question, > i'm sure you have a lot of better things to do that help a > beginner like me. We were all beginners at one time. Teaching people is rarely a waste of time unless they don't want to be taught. But you have to help us solve your problem. -- Grant Edwards grante Yow! While I'm in at LEVITTOWN I thought I'd visi.com like to see the NUCLEAR FAMILY!! From mnations at gmail.com Wed Mar 8 15:03:56 2006 From: mnations at gmail.com (Mudcat) Date: 8 Mar 2006 12:03:56 -0800 Subject: Need recs on the best graphing interface Message-ID: <1141848236.659041.267080@i40g2000cwc.googlegroups.com> Hi, I have looked through the previous suggestions on graphing modules and have been able to find some good suggestions. However I was wondering about something more specific. I am going to write a program that tracks stock prices and other financial related charts, so I need to use the classic stock chart. From the ones I've seen, the graphing modules deal mostly with scientific plotting and do not have the "high/low" type charts. Does anyone know of a module that contains this type of chart, or one that can be converted? I was hoping to find one that has done some of this before I start doing it myself. Thanks, Marc From godoy at ieee.org Sat Mar 4 08:42:36 2006 From: godoy at ieee.org (Jorge Godoy) Date: Sat, 04 Mar 2006 10:42:36 -0300 Subject: Package organization: where to put 'common' modules? References: <1141419542.750676.176150@z34g2000cwc.googlegroups.com> <44098830$1_3@newspeer2.tds.net> Message-ID: <87y7zq72cz.fsf@ieee.org> Kent Johnson writes: > What I do is run always from the base directory (violates your first > requirement). I make a util package to hold commonly used code. Then B and D > both use > from util import foo > > In Python 2.5 you will be able to say (in D, for example) > from ..util import foo > > http://www.python.org/peps/pep-0328.html I do work a bit different here. When two programs start sharing code, then I convert this code into a "library", i.e., I make it a module, put it in PYTHONPATH and then import it. Probably more than two projects will use it if two of them already are :-) -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From johnjsal at NOSPAMgmail.com Wed Mar 29 14:20:14 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 29 Mar 2006 19:20:14 GMT Subject: a hobbyist's dilemma In-Reply-To: <1143659005.902844.157320@u72g2000cwu.googlegroups.com> References: <6uAWf.1851$No6.41879@news.tufts.edu> <1143659005.902844.157320@u72g2000cwu.googlegroups.com> Message-ID: Enigma Curry wrote: > I would second the vote for pythonchallenge. It's what taught me > Python. > > The amazing thing about the python challenge is by the time your done > with it, you've gotten through a very large and diverse sampling of the > python docs. It really gave me a good understanding of all the things > that Python can do. You'll still want to read more traditional > tutorials and thoery as well, but that can wait, just play around with > it for a while. > Yup, stuck on the second exercise. I know mostly what to do, but there's one thing hanging me up, so time to search through the docs. :) From dongdonglove8 at hotmail.com Wed Mar 8 00:22:27 2006 From: dongdonglove8 at hotmail.com (dongdong) Date: 7 Mar 2006 21:22:27 -0800 Subject: how to download a zip or rar file to local machine using python? Message-ID: <1141795347.072982.216900@j52g2000cwj.googlegroups.com> I wrote as following: content=urllib2.urlopen("http://www.sdfagfa.org/asasg/a.zip").read() f=open("d:\\a.zip",'a+',1) f.writelines(content) the zip file has been download to my machine,but when be unzip , error occurs: " there is an error at the end of the file" From fredrik at pythonware.com Sat Mar 11 10:16:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 11 Mar 2006 16:16:11 +0100 Subject: why use special config formats? References: <1142002082.976945.261900@e56g2000cwe.googlegroups.com><1142004363.863051.29090@j33g2000cwa.googlegroups.com><1142010515.974623.207980@e56g2000cwe.googlegroups.com> <1142084683.820221.281860@j52g2000cwj.googlegroups.com> Message-ID: "gangesmaster" wrote: > > Binary configs only keep out legitimate users who don't have the time or > > ability to learn how to hack the binary format. Black hats and power users > > will break your binary format and hack them anyway. > > then you dont know what pickle is. pickle code is NOT python bytecode. > it's a bytecode they made in order to represent objects. you cannot > "exploit" in in the essence of running arbitrary code import pickle print pickle.loads("cos\nsystem\np0\n(S'echo really?'\np1\ntp2\nRp3\n.") From sybrenUSE at YOURthirdtower.com.imagination Fri Mar 10 10:10:09 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 10 Mar 2006 16:10:09 +0100 Subject: Which GUI toolkit is THE best? References: <441172c2$1@news1.ethz.ch> Message-ID: Thomas Guettler enlightened us with: > The licence for QT is GPL, this means you cannot use it in > commercial application. That is why I never looked at it. Ehmm... from their website: The Qt Commercial License is the correct license to use for the construction of proprietary, commercial software. The license allows you to: - Build commercial software and software whose source code you wish to keep private. - Freely choose licensing for the software you are writing (Proprietary, Open Source or both). - Be able to gain access to Qt Solutions, Trolltech support and commercial-only Qt components such as commercial database drivers and the Visual Studio Integration on Windows. 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 wkehowski at cox.net Thu Mar 16 12:35:19 2006 From: wkehowski at cox.net (wkehowski at cox.net) Date: 16 Mar 2006 09:35:19 -0800 Subject: Programming challenge: wildcard exclusion in cartesian products In-Reply-To: References: <1142507663.796075.212430@v46g2000cwv.googlegroups.com> Message-ID: <1142530519.761020.24960@i39g2000cwa.googlegroups.com> The point is to submit elegant code that showcases the features of each language. And the problem is, just to clarify, given a set WC of wildcards in any logical combination, and if WC(S^n) is the set all s in S^n that matches the wildcards, then efficiently generate the complement S^n\WC(S^n). You are free to restate the problem in any equivalent way. From eddie at holyrood.ed.ac.uk Fri Mar 10 07:41:56 2006 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 10 Mar 2006 12:41:56 +0000 (UTC) Subject: A better RE? References: Message-ID: "Fredrik Lundh" writes: >Eddie Corns wrote: >> >I want an re that matches strings like "21MAR06 31APR06 1236", >> >where the last part is day numbers (1-7), i.e it can contain >> >the numbers 1-7, in order, only one of each, and at least one >> >digit. I want it as three groups. I was thinking of >> >> Just a small point - what does "in order" mean here? if it means that eg 1362 >> is not valid then you're stuck because it's context sensitive and hence not >> regular. >> >> I can't see how any of the fancy extensions could help here but maybe I'm >> just lacking insight. >import re >p = re.compile("(?=[1234567])(1?2?3?4?5?6?7?)$") >def test(s): > m = p.match(s) > print repr(s), "=>", m and m.groups() or "none" >test("") >test("1236") >test("1362") >test("12345678") >prints >'' => none >'1236' => ('1236',) >'1362' => none >'12345678' => none > I know I know! I cancelled the article about a minute after posting it. Eddie From jearl at xmission.com Wed Mar 15 13:30:33 2006 From: jearl at xmission.com (Jason Earl) Date: Wed, 15 Mar 2006 11:30:33 -0700 Subject: Tried Ruby (or, "what Python *really* needs" or "perldoc!") References: <1142355126.757569.42160@i40g2000cwc.googlegroups.com> <1142397587.151040.35450@j33g2000cwa.googlegroups.com> <1142434139.499666.281590@v46g2000cwv.googlegroups.com> Message-ID: <87wtevv9va.fsf@workhorse.earlhome> "msoulier" writes: >> I have found the Python sidebar VERY helpful: > > Personally, I can't use local docs on my desktop as they may not be > the same version of the docs for the Python distro running on the > server that I'm deploying on. I usually go to python.org and use the > wayback machine to look at the old docs for the release that I'm on. Why don't you instead install the info version of the Python documentation on your server. Then you can do "info Python2.3-lib" and have at it. If you are hacking in emacs then this is about as slick a documentation system as you could ask for, but even if you use some other editor info is a much better documentation tool than man. > But, if Python would match Perl for docs available on the > command-line, then I'd have it all at my fingertips. I simply don't > understand why this is not being done. When I'm coding in C, I use > the manpages on the remote host so that I know the docs are correct > for my target. Why can't I do that in Python? It's yet another thing > that my Perl-using coworkers point out as a Python weakness. Python does match (and exceed) Perl for docs available on the command line. Once you get used to using the excellent info-based Python documentation using man is downright primitive. Jason From felipe.lessa at gmail.com Sun Mar 26 09:59:32 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 26 Mar 2006 11:59:32 -0300 Subject: wired md5 hashing problem In-Reply-To: <1143384987.7943.8.camel@uranos.pentacon.gov> References: <1143384987.7943.8.camel@uranos.pentacon.gov> Message-ID: <1143385172.21683.2.camel@kenshin> Em Dom, 2006-03-26 ?s 16:56 +0200, Matthias G?ntert escreveu: > so the format should be okay, but whats wrong with my piece of code?! It looks ok for me. What does md5sum gives as the sum? -- Felipe. From steven.bethard at gmail.com Tue Mar 14 17:10:55 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 14 Mar 2006 15:10:55 -0700 Subject: elementtree and gbk encoding In-Reply-To: <47osiqFgp2hlU1@uni-berlin.de> References: <47osiqFgp2hlU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Steven Bethard schrieb: >> I'm having trouble using elementtree with an XML file that has some >> gbk-encoded text. (I can't read Chinese, so I'm taking their word for >> it that it's gbk-encoded.) I always have trouble with encodings, so >> I'm sure I'm just screwing something simple up. Can anyone help me? >> >> Here's the interactive session. Sorry it's a little verbose, but I >> figured it would be better to include too much than not enough. I >> basically expected et.ElementTree(file=...) to fail since no encoding >> was specified, but I don't know what I'm doing wrong when I use >> codecs.open(...) > > The first and most important lesson to learn here is that well-formed > XML must contain a xml-header that specifies the used encoding. This has > two consequences for you: > > 1) all xml-parsers expect byte-strings, as they have to first read the > header to know what encoding awaits them. So no use reading the xml-file > with a codec - even if it is the right one. It will get converted back > to a string when fed to the parser, with the default codec being used - > resulting in the well-known unicode error. > > 2) your xml is _not_ well-formed, as it doesn't contain a xml-header! > You need ask these guys to deliver the xml with header. Of course for > now it is ok to just prepend the text with something like version="1.0" encoding="gbk"?>. But I'd still request them to deliver it > with that header - otherwise it is _not_ XML, but just something that > happens to look similar and doesn't guarantee to be well-formed and thus > can be safely fed to a parser. Thanks, that's very helpful. I'll definitely harrass the people producing these files to make sure they put encoding declarations in them. Here's what I get with the prepending hack: >>> et.fromstring('\n' + open(filename).read()) Traceback (most recent call last): File "", line 1, in ? File "C:\Program Files\Python\lib\site-packages\elementtree\ElementTree.py", line 960, in XML parser.feed(text) File "C:\Program Files\Python\lib\site-packages\elementtree\ElementTree.py", line 1242, in feed self._parser.Parse(data, 0) ExpatError: unknown encoding: line 1, column 30 Are the XML encoding names different from the Python ones? The "gbk" encoding seems to work okay from Python: >>> open(filename).read().decode('gbk') u'\nART242\n
\n \n
\n\n\n\n( (IP-HLN (LCP-TMP (IP (NP-PN-SBJ (NR \u4f0f\u660e\u971e)) \n\t\t (VP (VV \u83b7\u5f97) \n\t\t\t (NP-OBJ (NN \u5973\u5b50) \n\t\t\t\t (NN \u8df3\u53f0) \n\t\t\t\t (NN \u8df3\u6c34) \n\t\t\t\t (NN \u51a0\u519b)))) \n\t\t (LC \u540e)) \n (PU \uff0c) \n (NP-SBJ (NP-PN (NR \u82cf\u8054\u961f)) \n (NP (NN \u6559\u7ec3))) \n (VP (ADVP (AD \u70ed\u60c5)) \n (PP-DIR (P \u5411) \n\t\t (NP (PN \u5979))) \n (VP (VV \u795d\u8d3a))) \n (PU \u3002)) ) \n\n\n( (FRAG (NR \u65b0\u534e\u793e) \n (NN \u8bb0\u8005) \n (NR \u7a0b\u81f3\u5584) \n (VV \u6444) )) \n\n\n\n\n\n
\n' STeve From deets at nospam.web.de Thu Mar 23 07:39:25 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 23 Mar 2006 13:39:25 +0100 Subject: Probelem about image size and dimensions References: <1143109000.672508.175070@t31g2000cwb.googlegroups.com> <48fbg4Fjqn9hU1@uni-berlin.de> <1143111286.875298.277290@z34g2000cwc.googlegroups.com> <48fdmpFk0bbbU1@uni-berlin.de> <1143114499.640227.267150@u72g2000cwu.googlegroups.com> Message-ID: <48fj9iFjnjhpU1@uni-berlin.de> ChengGong wrote: > Diez, > > I asked the administrator that they won't allow me to import Image and > PIL in Zope. > I am wondering that how can I get the height and width and the size of > the image in this situation? > Can I just use to get Image's addtributs? No. At least not easily. You'd have to write the whole image-header loading yourself. Which is certainly more than a two-week-old python coder is capable of. If I were you I'd pester your sysadmins to allow you to create an external method - after all it is _their_ job to make you happy as a developer - IMHO. Diez From Allerdyce.John at gmail.com Sat Mar 11 00:12:57 2006 From: Allerdyce.John at gmail.com (Allerdyce.John at gmail.com) Date: 10 Mar 2006 21:12:57 -0800 Subject: put multiple condition in if statement Message-ID: <1142053977.812201.57640@i39g2000cwa.googlegroups.com> Hi, How can I put multiple condition in if statement? I try this, but I can't get that to work. if ( (str != " ") && (str != "") ): Any help is appreciated. Thank you. From fredrik at pythonware.com Fri Mar 24 03:19:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 24 Mar 2006 09:19:08 +0100 Subject: Strings and % sign fails - Help Please References: <1143168531.461348.130160@t31g2000cwb.googlegroups.com><87lkv0r1lk.fsf@ieee.org> <1143169736.507783.95460@z34g2000cwc.googlegroups.com> Message-ID: siasookhteh at gmail.com wrote: > heh.. It works except I am using psycopg.Binary(somebinarystructure), > and I am not really doing it by hand to just add the extra %, and > psycopg.Binary doesn't do it. I'd imagine it's a bug with psycopg > package. or a bug in your use of Binary. what exactly are you applying Binary to, and how do you pass the resulting adapter to execute ? From avenpace at gmail.com Wed Mar 22 04:49:07 2006 From: avenpace at gmail.com (avenpace at gmail.com) Date: 22 Mar 2006 01:49:07 -0800 Subject: Multifile EOF error References: <1142866966.526065.309210@t31g2000cwb.googlegroups.com> Message-ID: <1143020947.802146.196110@u72g2000cwu.googlegroups.com> > Try to trim down your script to the minimal code that produces the error > and post both. Copy'n'paste code and traceback, don't retype it. The code is kinda bit long so you can see the whole idea. I use some libgmail and twisted web #code start def displayComment(request): gmc = libgmail.GmailAccount(gmailacc, gmailpasswd) try: gmc.login() except: request.write("Cannot feed comment now, sorry") for tkey, tvals in request.args.items(): if tkey == "tiddler": for tval in tvals: tidlabel = tval else: request.write("Wrong url setting in the commen plugin") fold = gmc.getMessagesByLabel(tidlabel) for thread in fold: for msg in thread: msource = msg.source cmess = str(feedComment(msource)) print "abis manggil feed" fcmess = join(cmess) def feedComment(fsrcs): print fsrcs srcsw = file("/tmp/srcs" + magic + ".tmp_", "w") #creating and write the mess source srcsw.write(fsrcs) srcsw.close() srcs = file("/tmp/srcs" + magic + ".tmp_", "r") dstfile = file("/tmp/" + magic + ".tmp","w") src = multifile.MultiFile(srcs,0) print "diatas header" headers = mimetools.Message(src, src.seekable) print "dibawah header" if headers.getmaintype() != "multipart": print "message is not multipart :(" boundary = headers.getparam("boundary") if not boundary: print "meesage boundary not specified" src.push(boundary) src.next() headers = mimetools.Message(src, src.seekable) encode = headers.getencoding() if not encode: print "Unknown encoding mail" mimetools.decode(src, dstfile, encode) dstfile.close() dstread = file("/tmp" + magic + ".tmp", "r") mess = dstread.read() #removing all the file generated in the tmp dir os.remove("/tmp/srcs" + magic + ".tmp_") os.remove("/tmp" + magic + ".tmp") return mess +"\n\n" #end of code the error that I get is Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/twisted/internet/selectreactor.py", line 133, in doSelect _logrun(selectable, _drdw, selectable, method, dict) File "/usr/lib/python2.4/site-packages/twisted/python/log.py", line 56, in callWithLogger return callWithContext({"system": lp}, func, *args, **kw) File "/usr/lib/python2.4/site-packages/twisted/python/log.py", line 41, in callWithContext return context.call({ILogContext: newCtx}, func, *args, **kw) File "/usr/lib/python2.4/site-packages/twisted/python/context.py", line 31, in callWithContext return func(*args,**kw) --- --- File "/usr/lib/python2.4/site-packages/twisted/internet/selectreactor.py", line 139, in _doReadOrWrite why = getattr(selectable, method)() File "/usr/lib/python2.4/site-packages/twisted/internet/tcp.py", line 351, in doRead return self.protocol.dataReceived(data) File "/usr/lib/python2.4/site-packages/twisted/protocols/basic.py", line 221, in dataReceived why = self.lineReceived(line) File "/usr/lib/python2.4/site-packages/twisted/web/http.py", line 961, in lineReceived self.allContentReceived() File "/usr/lib/python2.4/site-packages/twisted/web/http.py", line 1002, in allContentReceived req.requestReceived(command, path, version) File "/usr/lib/python2.4/site-packages/twisted/web/http.py", line 557, in requestReceived self.process() File "libgmail-0.1.4/servetiddly.py", line 180, in process handler(self) File "libgmail-0.1.4/servetiddly.py", line 149, in displayComment cmess = str(feedComment(msource)) File "libgmail-0.1.4/servetiddly.py", line 118, in feedComment src.next() File "/usr/lib/python2.4/multifile.py", line 120, in next while self.readline(): pass File "/usr/lib/python2.4/multifile.py", line 80, in readline raise Error, 'sudden EOF in MultiFile.readline()' multifile.Error: sudden EOF in MultiFile.readline() From ramen at lackingtalent.com Wed Mar 1 16:53:54 2006 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 1 Mar 2006 15:53:54 -0600 Subject: Is it better to use class variables or pass parameters? In-Reply-To: <1141241522.096240.53380@v46g2000cwv.googlegroups.com> References: <1141241522.096240.53380@v46g2000cwv.googlegroups.com> Message-ID: On Wed, 1 Mar 2006, Derek Basch wrote: > This one has always bugged me. Is it better to just slap a "self" in > front of any variable that will be used by more than one class method > or should I pass around variable between the methods? As a general rule, I only turn a parameter into an instance variable when it would otherwise be a parameter of all (or nearly all) methods. Though this is perhaps an overly mechanical perspective, I like to think of instance variables as implicit parameters to every method. It helps me keep scope under control and encourages better cohesion. -- .:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:. "one man's constant is another man's variable" - alan perlis From __peter__ at web.de Tue Mar 28 06:06:06 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 28 Mar 2006 13:06:06 +0200 Subject: Link to Daily Python-URL from www.python.org? References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <4427d287$0$38669$edfadb0f@dread12.news.tele.dk> Message-ID: Tim Churches wrote: > Am I correct in thinking that there is no longer any link from anywhere > on the Python Web site at http;//www.python.org to the Daily Python-URL > at http://www.pythonware.com/daily/ ? There is no sign of it on the > Community page, nor any reference to it at http://planet.python.org/ See http://www.python.org/links/ All links provided on that page would benefit from a short description. Peter From ramkumar at aapt.net.au Sat Mar 4 17:54:42 2006 From: ramkumar at aapt.net.au (Ramkumar Nagabhushanam) Date: Sun, 5 Mar 2006 08:54:42 +1000 Subject: CallBack Message-ID: <440A1AB2.000007.62180@RAMKUMAR> Hello All, I am trying to integrate the ftpclient (in ftplib) with an application that has been written I C/C++. I am able to delete,send change working directories etc. When I receive data back from the server i.e. Retrieve files, get a directory listing) I want to pass a callback function to the ftpclient so that the output does not get displayed on stdout. The code I have written is as shown below. Can anyone out there give me advise on how to write "c_function" that is called in ftpTest::DoesFileExist ?Any help will be most appreciated. The code runs under windows and is compiled with VC++ 6.0. THe code is as shown below. Regards, Ram >>>>>>>>>>>>>>>>>>> CODE START >>>>>>>>>>>>>>>>>>> // test.cpp : Defines the entry point for the console application. // #include #include #include #include #include #include "C:\Python24\include\Python.h" Class ftpTest { Private: PyObject *_FTP; PyObject *_callBack; Public: FtpTest (const char * ipAddress, const char * username, const char * password); // Open the FTP connection, Initialize python interpreter ~ftpTest (); // Close connection and finalize python interpreter Int Close (); Int GetFile (const char * fileName); Int PutFile (const char * fileName); Int ChangeDir (const char * dirName); Int DoesFileExist (const char * fileName); Int DeleteFile (const char * fileName); Int ChangePermissions (const char * fileName, const char * permissions); }; FtpTest::ftpTest (const char * ipAddress, const char * username, const char * password) { PyObject *modname, *mod, *func, *mdict, *pArgs, *pValue; // Initialize the python interpreter Py_Initialize(); Modname = PyString_FromString("ftplib"); If (modname == NULL) { // Log an error } Else { Mod = PyImport_Import (modname); } If (mod) { Mdict = PyModule_GetDict (mod); Func = PyDict_GetItemString (mdict, "FTP"); If (func) { Printf ("I am here -- 1\n"); } Const char *arguments[] = {ipAddress, username, password}; PArgs = PyTuple_New (3); For (int I = 0; I < 3; ++I) { PValue = PyString_FromString(arguments[I]); If (!pValue) { Py_DECREF(pArgs); Py_DECREF(mod); } /* pValue reference stolen here: */ PyTuple_SetItem(pArgs, I, pValue); } _FTP = PyObject_CallObject (func, pArgs); If (_FTP != NULL) { Printf ("I am here -- 2\n"); } } } FtpTest::~ftpTest () { //Py_Finalize(); } Int ftpTest::Close () { Return (1); } Int ftpTest::ChangeDir (const char * dirName) { PyObject *t = PyObject_CallMethod (_FTP, "cwd", "(S)", dirName); Return (1); } Int ftpTest::DeleteFile (const char * fileName) { PyObject *t = PyObject_CallMethod (_FTP, "delete", "(S)", fileName); Return (1); } Int ftpTest::PutFile (const char * fileName) { PyObject * py_file = PyFile_FromString ((char *)fileName, "rb"); Std::string S("STOR "); s += fileName; PyObject * t = PyObject_CallMethod (_FTP, "storlines", "(sO)", S.c_str(), py_file); Return (1); } Int ftpTest::ChangePermissions (const char * fileName, const char * permissions) { Std::string S("SITE"); s += " chmod "; s += permissions; s += " "; s += fileName; PyObject * t = PyObject_CallMethod (_FTP, "sendcmd", "(S)", S.c_str()); Return (1); } Int ftpTest::GetFile (const char * fileName) { // TODO: Implement callback #if 0 PyObject *t = PyObject_CallMethod (_FTP, "retrlines", "(S)", "RETR ram.txt ); #endif Return (1); } PyObject * c_function(char * data) { // Process the data received in "data" Return (NULL); } Int ftpTest::DoesFileExist (const char * fileName) { // Just get the list PyObject *t = PyObject_CallMethod (_FTP, "retrlines", "(sO)", "LIST", c_function); If (t == NULL) { Printf ("I am here -- 4\n"); } Return (1); } Int main () { FtpTest ftpClient("127.0.0.1", "xxx", "yyyy"); FtpClient.DoesFileExist(NULL); Return (1); } >>>>>>>>>>>>>>>>>>> CODE END >>>>>>>>>>>>>>>>>>>>> From barmenkov at bpc-dot-ru.no-spam.invalid Wed Mar 15 08:10:32 2006 From: barmenkov at bpc-dot-ru.no-spam.invalid (PyDenis) Date: 15 Mar 2006 13:10:32 GMT Subject: WORKAROUND References: <4417d37c$0$76222$892e7fe2@authen.yellow.readfreenews.net> Message-ID: <44181248$1$76048$892e7fe2@authen.yellow.readfreenews.net> > Fredrik Lundhwrote: Could you perhaps use basic netiquette stuff, such as sticking to the same sub- > ject line for followup posts in the same thread, and including a least some trace > of the post you're commenting on ? > > (this would be less of a problem if everyone was reading your posts in a news- > reader, but this group is available in many different forms...) > > Excuse me, please. I mean, that 1. When I post new message to WEBFORUM (not a Mailing List nor News Group) not to include even part of message. 2. About subject line: if this forum huge depends from subject line, this field must be disabled or set to "RE: % "+ (orig_msg.subject) by forum admins. Forum using some webforum engine, and easiest way to format messages - tune it up accurately instead of messaging about netiquette. 3. I receive message about topic posts without host name, so could go in Browser History to find it. I mean, misplaced 'netiquette' eclipsed by this bug: Hello, You are receiving this email because you are watching the topic, "Re: WORKAROUND" at niXforums. This topic has received a reply since your last visit. You can use the following link to view the replies made, no more notifications will be sent until you visit the topic. http:///files/forum/viewtopic.php?p=730860#730860 If you no longer wish to watch this topic you can either click the "Stop watching this topic link" found at the bottom of the topic above, or by clicking the following link: http:///files/forum/viewtopic.php?t=136721&unwatch=topic -- Thanks, The Management Please, sorry for my english. From john_sips_teaz at yahooz.com Tue Mar 14 02:41:54 2006 From: john_sips_teaz at yahooz.com (John M. Gabriele) Date: Tue, 14 Mar 2006 02:41:54 -0500 Subject: Basic python help In-Reply-To: References: <2955b$44166cc5$506c2949$25559@news.chello.at> Message-ID: (Please don't top-post -- fixed) Kevin Feng wrote: > > > On 3/14/06 2:12 AM, in article 2955b$44166cc5$506c2949$25559 at news.chello.at, > "Gregor Horvath" wrote: > > >>Kevin Feng schrieb: >> >> >>>More information about this error may be available in the server error log. >>> >>> >>> >>>Any suggestions? Much thanks. >>> >> >>What does the error log of the webserver say? >> >>-- >>Greg > > No idea, I do not have permission to access the error log. > > In your cgi script, try putting "import cgitb; cgitb.enable()" on the next line right after "import cgi". Also try changing your POST to GET. ---John -- (remove zeez if demunging email address) From tim.peters at gmail.com Thu Mar 23 00:22:13 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 23 Mar 2006 00:22:13 -0500 Subject: C API: Testing my reference counting In-Reply-To: <1143090161.561003.74750@g10g2000cwb.googlegroups.com> References: <1142836476.822094.3200@v46g2000cwv.googlegroups.com> <441E67C9.6040908@v.loewis.de> <1143090161.561003.74750@g10g2000cwb.googlegroups.com> Message-ID: <1f7befae0603222122p305584f0madd1957f08c90967@mail.gmail.com> [lord trousers] >>> Is there a way I can get hold of these kinds of statistics for >>> debugging? [Martin v. L?wis] >> This is best done when Python is build in debug mode. >> sys.gettotalrefcount then gives you the number of INCREF >> calls for which no DECREF has been made; you said that >> this shouldn't change. >> >> If it does change, sys.get_counts() will give you the >> number of objects per type. >> >> Furthermore, sys.getobjects() will give you a list of >> all objects allocated (excluding the result list). [lord trousers] > Wonderful! That's just what I was looking for. > > Is this kind of thing documented somewhere public? (As attributes that > only show up in the debug build, they aren't documented in the regular > library docs.) There might be more nifty goodies like this, and I'd > like to check them out. Actually, sys.getcounts() only exists in a COUNT_ALLOCS build (which can be combined with a debug build, but is not implied by a debug build). All that (and other esoterica) is documented in Misc/SpecialBuilds.txt, in any Python source distribution. The Python Windows installer does not contain that file. From steve at holdenweb.com Fri Mar 10 11:02:22 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 10 Mar 2006 16:02:22 +0000 Subject: Performance impact of using decorators In-Reply-To: <1142003515.886709.290360@j33g2000cwa.googlegroups.com> References: <1142003515.886709.290360@j33g2000cwa.googlegroups.com> Message-ID: vinjvinj wrote: > I'm building an application with cherrypy and have started using > decorators quite extensively. A lot of my exposed functions look like: > > @expose > @startTransactrionAndBuildPage > @partOfTabUi(tabId) > @convert(arg1=int, arg2=str) > def do_main_page(self, arg1, arg2): > some code > > > I've become really fond of decorators and use them quite a lot. I've > also ready that function calls are expensive in python. In the above > example, does the interpreter call 5 different functions? > Without reading your code I can't be sure, but this is sure looking like the classic "to a man with only a hammer all problems look like a nail" solution. I'm not going to tell you that decorators aren't the answer to all programming problems, because you already know that in your heart :-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From john_sips_tea at yahoo.com Tue Mar 14 12:25:07 2006 From: john_sips_tea at yahoo.com (john_sips_tea at yahoo.com) Date: 14 Mar 2006 09:25:07 -0800 Subject: Tried Ruby (or, "what Python *really* needs" or "perldoc!") In-Reply-To: <47obg1Fgjd6kU1@uni-berlin.de> References: <1142355126.757569.42160@i40g2000cwc.googlegroups.com> <47obg1Fgjd6kU1@uni-berlin.de> Message-ID: <1142357107.619114.180650@i40g2000cwc.googlegroups.com> Thanks Diez! Epydoc looks great. Can we use epytext to generate output suitable for a manpage? Do you prefer epytext or reST? From lycka at carmen.se Thu Mar 9 06:04:15 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 09 Mar 2006 12:04:15 +0100 Subject: Alternative style sheets - Re: New python.org website In-Reply-To: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> References: <1141707312.960344.201560@p10g2000cwp.googlegroups.com> Message-ID: Phoe6 wrote: > beta.python.org evolved very nice and noticed today the new python.org > website going live. There is a change in the look n feel, wherein it > looks "more official" and maximum possible information about python is > now directly accessible from the home page itself. Kudoes to the > design team. I also feel this is a big improvement. I know that a web site like this needs constant nurturing, so I hope that it's been developed in such as way that it will be easier to maintain it and to involve more contributors. Concerning style sheets, it's pretty trivial to make several style sheets and let people use the one they like best. If we enable that, it should also be simple to see from the web site statistics which style sheet people prefer. Then we can use the most popular style sheet as the default! Since people have different tastes, different screens with various resolutions and colors etc, darker or lighter rooms, might want different styles for on-screen viewing and on paper etc, I think it would be a good idea to have several styes even if there is no ambivalence concerning what look we want. From volcs0 at gmail.com Sat Mar 18 23:31:42 2006 From: volcs0 at gmail.com (volcs0 at gmail.com) Date: 18 Mar 2006 20:31:42 -0800 Subject: Can I use a conditional in a variable declaration? In-Reply-To: <441cd5dc$1_2@newspeer2.tds.net> References: <1142741039.554379.182170@g10g2000cwb.googlegroups.com> <441cd5dc$1_2@newspeer2.tds.net> Message-ID: <1142742702.672907.222700@p10g2000cwp.googlegroups.com> Kent - Thanks for the quick reply. I tried the and/or trick - it does work. But you're right - more trouble than its worth.... So for now, I did it "the long way". It looks like (see below), this functionality will be added in soon. Thanks for the quick help. -sam From ZeD.est.Deus at gmail.com Sun Mar 19 10:36:56 2006 From: ZeD.est.Deus at gmail.com (ZeD) Date: Sun, 19 Mar 2006 15:36:56 GMT Subject: Initializing a list of lists References: <1142782140.389645.23500@z34g2000cwc.googlegroups.com> Message-ID: Ciao, tkpmep at hotmail.com! Che stavi dicendo? > Is there a simple way to create a list of independent lists? N=3 x=[[0] for e in range(N)] -- Up da 1 giorno, 3 ore, 43 minuti e 10 secondi From joel.hedlund at gmail.com Tue Mar 28 05:12:52 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Tue, 28 Mar 2006 12:12:52 +0200 Subject: Difference between 'is' and '==' In-Reply-To: <1143462121.828462.34290@v46g2000cwv.googlegroups.com> References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <1143462121.828462.34290@v46g2000cwv.googlegroups.com> Message-ID: > a is None > > is quicker than > > a == None I think it's not such a good idea to focus on speed gains here, since they really are marginal (max 2 seconds total after 10000000 comparisons): >>> import timeit >>> print timeit.Timer("a == None", "a = 1").timeit(int(1e7)) 4.19580316544 >>> print timeit.Timer("a == None", "a = None").timeit(int(1e7)) 3.20231699944 >>> print timeit.Timer("a is None", "a = 1").timeit(int(1e7)) 2.37486410141 >>> print timeit.Timer("a is None", "a = None").timeit(int(1e7)) 2.48372101784 Your observation is certainly correct, but I think it's better applied to more complex comparisons (say for example comparisons between gigantic objects or objects where value equality determination require a lot of nontrivial computations). That's where any real speed gains can be found. PEP8 tells me it's better style to write "a is None" and that's good enough for me. Otherwise I try to stay away from speed microoptimisations as much as possible since it generally results in less readable code, which in turn often results in an overall speed loss because code maintenance will be harder. Cheers! /Joel Hedlund From max at knirz.de Sat Mar 18 19:33:08 2006 From: max at knirz.de (Max Kubierschky) Date: Sun, 19 Mar 2006 01:33:08 +0100 Subject: epydoc: links to other methods/classes with reStructuredText Message-ID: <441CA6C4.2070809@knirz.de> Hi, I try to use epydoc with reStructuredText. It works fine, my only problem is that I couldn't figure out the syntax for links to other methods or classes. Any hints? Max P.S: Where is the correct platform for discussing epydoc? From reply.in.the.newsgroup at my.address.is.invalid Sun Mar 5 08:52:37 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sun, 05 Mar 2006 14:52:37 +0100 Subject: How to except the unexpected? References: Message-ID: <6jql02hf7cni91ddfi54mll9iqebps5d3n@4ax.com> Steven D'Aprano: >The OP is doing it because catching all exceptions masks bugs. There are >certain exceptions which should be allowed through, as they indicate a bug >in the OP's code. Normally the tactic is to catch only the exceptions you >are interested in, and let everything else through, but the OP needs to >catch all exceptions because there are rare exceptions which he can't >predict in advance. To add to that explanation: this is in a multithreaded ZODB-application. When an unexpected exception occurs and remains uncaught, a thread terminates, causing the thread pool to wait forever since some thread is not consuming its termination request from the queue, causing the app to not terminate, causing the ZODB to remain locked, causing other apps to fail, causing havoc on my server. I don't mind this when it's caused by a bug in my code, since that creates the sense of urgency required to fix the bug. But it's annoying when it happens because of an I/O exception caused by some other guys bug on the other side of the planet :-) -- Ren? Pijlman From g.brandl-nospam at gmx.net Sun Mar 19 05:38:29 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sun, 19 Mar 2006 11:38:29 +0100 Subject: Can I use a conditional in a variable declaration? In-Reply-To: References: <1142741039.554379.182170@g10g2000cwb.googlegroups.com> Message-ID: <484ql6Fi4kq1U1@individual.net> Jeffrey Schwab wrote: > volcs0 at gmail.com wrote: > >> I want the equivalent of this: >> >> if a == "yes": >> answer = "go ahead" >> else: >> answer = "stop" >> >> in this more compact form: >> >> a = (if a == "yes": "go ahead": "stop") >> >> is there such a form in Python? I tried playing around with lambda >> expressions, but I couldn't quite get it to work right. > > Rather than lambda, this merits a named function. You only have to > define it once. > > def mux(s, t, f): > if s: > return t > return f But be aware that this is not a complete replacement for a syntactic construct. With that function, Python will always evaluate all three arguments, in contrast to the and/or-form or the Python 2.5 conditional. You can show this with test = mux(False, 1/0, 1) and test = False and 1/0 or 1 Georg From johnjsal at NOSPAMgmail.com Wed Mar 8 20:17:43 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Mar 2006 20:17:43 -0500 Subject: is there any overheard with try/except statements? In-Reply-To: References: Message-ID: John Salerno wrote: > One of the things I learned with C# is that it's always better to handle > any errors that might occur within the codes itself (i.e. using if > statements, etc. to catch potential out of range indexing) rather than > use too many try/catch statements, because there is some overhead every > time the program encounters the try. > > Is this the case at all with Python, in terms of extra work or slower > speed? Or is try/except implemented differently in Python than it is in > other languages, so that it runs just like any other code? > > Thanks. Thanks guys! I had a feeling exceptions were nothing like in C languages (i.e. a pain to deal with). :) From lycka at carmen.se Mon Mar 20 05:23:57 2006 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 20 Mar 2006 11:23:57 +0100 Subject: Is there no end to Python? In-Reply-To: References: <1142622194.560240.4330@j52g2000cwj.googlegroups.com> Message-ID: John Salerno wrote: > But isn't Python sort of known for the opposite, i.e. 'one simple way', > or something to that effect? If we compare it with the "opposite" language--Perl, and think of these languages as natural languages, rather than programming languages, Perl's inventor Larry Wall, felt that having a lot of synonymns and allowing a lot of flexibility in word order etc, would make it easier to express one's ideas well. Python's inventor Guido van Rossum took a different approach. With fewer synonyms and a less redundant grammer, it will be easier to master the language, and certainly easier to read texts written by others. I don't know, but I suspect that the difference in approach is rooted in Guido's understanding that we typically spend much more time reading source code than we spend writing source code. As it turns out, having fewer synonyms and grammatic variants, does not make it harder to come up with different solutions to problems. It rather seems that the lack of complexity that a simpler grammer leads to makes it much easier to try out different solutions. From felipe.lessa at gmail.com Sat Mar 18 08:40:48 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sat, 18 Mar 2006 10:40:48 -0300 Subject: How to convert In-Reply-To: <1142689077.3928.0.camel@kenshin> References: <1142687566.540612.83480@z34g2000cwc.googlegroups.com> <1142689077.3928.0.camel@kenshin> Message-ID: <1142689248.3928.2.camel@kenshin> Em S?b, 2006-03-18 ?s 10:38 -0300, Felipe Almeida Lessa escreveu: > Em S?b, 2006-03-18 ?s 05:12 -0800, Lad escreveu: > > How can I covert in Python a variable of a long type to variable of > > Integer type? > > You can do "int(variable)", but it can't be always done (for example, > when variable > MAX_INT): A more concrete example: >>> int(2**31) 2147483648L >>> int(2**31-1) 2147483647 >>> int(-2**31) -2147483648 >>> int(-2**31-1) -2147483649L From michael at stroeder.com Thu Mar 30 03:06:39 2006 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 30 Mar 2006 10:06:39 +0200 Subject: ldap usage In-Reply-To: References: Message-ID: Jed Parsons wrote: > > As an addendum, I discovered one little gotcha, namely that this: > > l.bind_s(username, password, ldap.AUTH_SIMPLE) > > throws an ldap.INVALID_CREDENTIALS error if the password contains the > wrong text, but works if the password is empty. I guess this is > tantamount to binding as ("", ""), but I wasn't expecting it; I figured > if a username was specified, the password would have to agree. Yes, this is by design. Empty cred means just switching to anon bind. LDAP was not intended to be used for password checking at that time. Which LDAP server are you using? You can switch off this behaviour with OpenLDAP. See man 5 slapd.conf, allow . > So my > little authentication example also needs to test for empty passwords. Yes! Ciao, Michael. From no-spam at no-spam-no-spam.com Thu Mar 16 08:14:37 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 16 Mar 2006 14:14:37 +0100 Subject: A Frame-space syntax ? - Re: global, globals(), _global ? In-Reply-To: <1hc97un.15qyd7bycer0fN%aleaxit@yahoo.com> References: <1hc8e79.imz7zd16x7t3sN%aleaxit@yahoo.com> <1hc97un.15qyd7bycer0fN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > robert wrote: > ... >>I think its good to leave the default global binding (that is probably >>whats Guido doesn't want to give up for good reason) > > > Then, on the principle that there should be preferably only one obvious > way to do something, we'll never have an _global object as you propose > (even by any other and much better name;-), because it systematically > produces TWO equally obvious or unobvious way to access globals. a path to the globals whould maybe not much different from an alternate __dict__ or globals() access. and see below .. >>Yet frames could expose their top-dict anyway as a virtual inspection >>object (__l/__l_ or __f_stack[-2]) . Or at least writing to >>locals() could be defined as writing to the top-frame-locals. >>Sub-Frames could write free there (its a rare & conscious task anyway) >>and the Frame itself could read either way. > > > Not sure I entirely understand what you're proposing, but locals access > must remain compile-time-optimized for crucial practical reasons, so > "writing to locals()" just will not work right. Why will a definite write to _certain_ top local dict consume any extra time? The target can still be directed fix at compile time. See below. >>Another ugly possibilties maybe by enriching variable assignment. >> >>Maybe '=' can be enriched like .= ..= := =: ::= =:: xxx-set ... etc. >>in order to be an expression with result value and to allow to writing >>to certain namspaces. > > > Ugly enough that Guido has never wanted to entertain such possibilities Maybe a syntax could be applied which is already known for float litterals and which seems to be intuitive and compatible to me: a=1 .a=1 # same d=5 def f() b=1 .b=1 # same print a print ..a # same ..a += 1 # compile-time known: its the global! def g(): ..b=2 # f-local b ! ..c=3 # write a 'free local' into f-locals ..d=4 ...a += 1 # the compiler knows: its global! g() print b # local print 1 + .c # ok print c # error!, but thats acceptable print d # global print .d # local!, but thats acceptable This syntax shows some kind of self-similarity: * a dot . always references a definite dict/namespace/obj (or a float) * a free dot . simply references the top local dictionary (or a float) * more dots step back through the frame stack * If no dot is there the usual "automatic name space" is assumed No old code would be broken. As far as I see this would not slow down the interpreter at run time (except maybe for the new "..b=" intermediate local write's) Robert From jeff at schwabcenter.com Fri Mar 17 23:23:10 2006 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Sat, 18 Mar 2006 04:23:10 GMT Subject: Python execution problem In-Reply-To: <1142642239.757552.44260@z34g2000cwc.googlegroups.com> References: <1142642239.757552.44260@z34g2000cwc.googlegroups.com> Message-ID: mailpitches at email.com wrote: > Using OSX 10.4.5 > > This is more of a unix/tcsh question than a python question. > Somehow I got to the point where I have two files 'a.py' and 'b.py' > which have identical contents and permissions, but one refuses to > execute: > > [blah:/Library/WebServer/CGI-Executables] me% a.py > tcsh: a.py: Command not found. > [blah:/Library/WebServer/CGI-Executables] me% b.py > okay > [blah:/Library/WebServer/CGI-Executables] me% > > Could someone enlighten me about how the shell knows to execute a > script? I always assumed it was just the extension, but this seems to > prove me wrong. It checks each directory in your path for an executable file with the name you specified. Each file has a set of associated bits to tell whether it is executable (or readable or writable), and by whom. To add execute permission to a.py, try this: chmod +x a.py FYI, it's not a great idea to rely on the current directory (.) being in your path. You might want to type it explicitly, e.g ./a.py instead of a.py. From sjuranic at gmail.com Fri Mar 17 10:32:52 2006 From: sjuranic at gmail.com (Steve Juranich) Date: Fri, 17 Mar 2006 08:32:52 -0700 Subject: Converting to ARGB and writing to a bitmap References: <1142555028.430564.4320@p10g2000cwp.googlegroups.com> Message-ID: heathimself at gmail.com wrote: > Hi, > I don't know what type of files they are, but the script allows me to > save to a bitmap just fine. But I do know they need to be in RGBA 4444 > format, so I've followed what most of the tutorials for RGBA > conversions said to do...shifting the bytes. > > The major problem is that everything is in green, it's shifted up by x > pixels, and it's..um..flipped from left to right. I've been working on > this for a few weeks now and any insight to the problem is greatly > appreciated. > > http://www.geocities.com/fisherdude_99/TestImg.zip This doesn't really answer your question, but have you looked into PIL yet? http://www.pythonware.com/products/pil/index.htm (except, hmmm.... it looks like the web site is down right now. Check back later?) It's got a bunch of different formats supported natively and makes image processing work a lot easier in some respects. -- Steve Juranich Tucson, AZ USA From sybrenUSE at YOURthirdtower.com.imagination Tue Mar 28 16:22:28 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 28 Mar 2006 23:22:28 +0200 Subject: CGI redirection: let us discuss it further References: <1143480299.024145.272600@u72g2000cwu.googlegroups.com> <1143566506.253970.172230@z34g2000cwc.googlegroups.com> Message-ID: and-google at doxdesk.com enlightened us with: > What's wrong with the redirection page? > > If there's really a necessary reason for not using an HTTP redirect > (for example, needing to set a cookie, which doesn't work > cross-browser on redirects), the best bet is a page containing a > plain link and